I would like to get the first item from a list matching a condition. It\'s important that the resulting method not process the entire list, which could be quite large. For e
Similar to using ifilter
, you could use a generator expression:
>>> (x for x in xrange(10) if x > 5).next()
6
In either case, you probably want to catch StopIteration
though, in case no elements satisfy your condition.
Technically speaking, I suppose you could do something like this:
>>> foo = None
>>> for foo in (x for x in xrange(10) if x > 5): break
...
>>> foo
6
It would avoid having to make a try/except
block. But that seems kind of obscure and abusive to the syntax.