views:

118

answers:

1

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.

+7  A: 
>>> lista = ['a', 'b', 'foo', 'c', 'd', 'e', 'bar']
>>> next(i for i in lista if len(i) > 2)
'foo'
SilentGhost
Note that the next function was added in 2.6. If you need compatibility with 2.5 or 2.4 then use `(i for i in lista if len(i) > 2).next()`
Dave Kirby
Always forgetting generators...
Phil H