Jonathan Livni
Jonathan Livni

Reputation: 107112

Python - Finding index of first non-empty item in a 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

Upvotes: 10

Views: 8984

Answers (6)

Daniel Exxxe
Daniel Exxxe

Reputation: 69

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_):
    ...

Upvotes: 1

Philipp
Philipp

Reputation: 49822

next(i for i, v in enumerate(list) if v)

Upvotes: 0

SilentGhost
SilentGhost

Reputation: 319661

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

Upvotes: 20

Joe Kington
Joe Kington

Reputation: 284662

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)

Upvotes: 6

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798804

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

Upvotes: 1

Jonathan Livni
Jonathan Livni

Reputation: 107112

try:
    i = next(i for i,v in enumerate(list_) if v)
except StopIteration:
    # Handle...

Upvotes: 2

Related Questions