Is there an easier way to get the first appearance of something?

I have a list that contains several things:

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

      

I would like to get the first item in a list that the predicate executes, eg len(item) > 2

. Is there an easier way to do this than itertools' dropwhile and next?

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

      

I used it first [item for item in lista if len(item)>2][0]

, but it requires python to generate the entire list first.

+2


a source to share


1 answer


>>> lista = ['a', 'b', 'foo', 'c', 'd', 'e', 'bar']
>>> next(i for i in lista if len(i) > 2)
'foo'

      



+7


a source







All Articles