Python - finding the index of the first non-empty element in a list

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

For example, when

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

The correct non-empty index should be:

 3 
+7
python list
source share
5 answers
 >>> lst = [None,[],None,[1,2],'StackOverflow',[]] >>> next(i for i, j in enumerate(lst) if j) 3 

if you do not want to raise a StopIteration error, just specify the default value for the next function:

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

PS do not use list as a variable name, it is a shadow inline.

+15
source share

One of the relatively elegant ways to do this:

 map(bool, a).index(True) 

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

+5
source share
 try: i = next(i for i,v in enumerate(list_) if v) except StopIteration: # Handle... 
+2
source share
 next(i for (i, x) in enumerate(L) if x) 
+1
source share
 next(i for i, v in enumerate(list) if v) 
0
source share

All Articles