Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Finding index of first non-empty item in a list

Tags:

python

list

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
like image 600
Jonathan Livni Avatar asked Jul 12 '10 15:07

Jonathan Livni


3 Answers

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

like image 139
SilentGhost Avatar answered Oct 14 '22 23:10

SilentGhost


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)

like image 44
Joe Kington Avatar answered Oct 14 '22 22:10

Joe Kington


try:
    i = next(i for i,v in enumerate(list_) if v)
except StopIteration:
    # Handle...
like image 28
Jonathan Livni Avatar answered Oct 14 '22 22:10

Jonathan Livni