Is there a neater way to get the first occurrence of something?

Posted by Phil H on Stack Overflow See other posts from Stack Overflow or by Phil H
Published on 2010-05-04T10:00:58Z Indexed on 2010/05/04 10:08 UTC
Read the original article Hit count: 171

Filed under:
|
|

I have a list which contains a number of things:

lista = ['a', 'b', 'foo', 'c', 'd', 'e', 'bar']

I'd like to get the first item in the list that fulfils a predicate, say len(item) > 2. Is there a neater way to do it than itertools' dropwhile and next?

first = next(itertools.dropwhile(lambda x: len(x) <= 2, lista))

I did use [item for item in lista if len(item)>2][0] at first, but that requires python to generate the entire list first.

© Stack Overflow or respective owner

Related posts about python

Related posts about iterators