10

What would be the most efficient\elegant way in Python to find the index of the first non-empty item in a list?

For example, with

list_ = [None,[],None,[1,2],'StackOverflow',[]]

the correct non-empty index should be:

3

6 Answers 6

20
>>> lst = [None,[],None,[1,2],'StackOverflow',[]]
>>> next(i for i, j in enumerate(lst) if j)
3

if you don't want to raise a StopIteration error, just provide default value to the next function:

>>> next((i for i, j in enumerate(lst) if j == 2), 42)
42

P.S. don't use list as a variable name, it shadows built-in.

Sign up to request clarification or add additional context in comments.

Comments

6

One relatively elegant way of doing it is:

map(bool, a).index(True)

(where "a" is your list... I'm avoiding the variable name "list" to avoid overriding the native "list" function)

2 Comments

that only works in python-2.x and anyway it builds the whole list of boolean values.
@SilentGhost - True. I didn't realize that map had changed in python3.
2
try:
    i = next(i for i,v in enumerate(list_) if v)
except StopIteration:
    # Handle...

Comments

1
next(i for (i, x) in enumerate(L) if x)

Comments

1

for python 3.x @Joe Kington solution is

list(map(bool, list_)).index(True)

Also consider working with values instead of indexes

for value in filter(bool, list_):
    ...

1 Comment

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
0
next(i for i, v in enumerate(list) if v)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.