tags:

views:

85

answers:

5

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  A: 
>>> 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.

SilentGhost
One vote up and one applause for the brevity and exactness.
Erik Escobedo
@SilentGhost - You're right! changed from list to list_ (in accord to PEP8)
Jonathan
+1  A: 
try:
    i = next(i for i,v in enumerate(list_) if v)
except StopIteration:
    # Handle...
Jonathan
+1  A: 
next(i for (i, x) in enumerate(L) if x)
Ignacio Vazquez-Abrams
+2  A: 

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)

Joe Kington
that only works in python-2.x and anyway it builds the whole list of boolean values.
SilentGhost
@SilentGhost - True. I didn't realize that map had changed in python3.
Joe Kington
A: 
next(i for i, v in enumerate(list) if v)
Philipp