How can I get a Python generator to return None rather than StopIteration? How can I get a Python generator to return None rather than StopIteration? python python

How can I get a Python generator to return None rather than StopIteration?


If you are using Python 2.6+ you should use the next built-in function, not the next method (which was replaced with __next__ in 3.x). The next built-in takes an optional default argument to return if the iterator is exhausted, instead of raising StopIteration:

next((i for i, v in enumerate(a) if i == 666), None)


You can chain the generator with (None,):

from itertools import chaina = [1,2,3,4]print chain((i for i, v in enumerate(a) if v == 6), (None,)).next()

but I think a.index(2) will not traverse the full list, when 2 is found, the search is finished. you can test this:

>>> timeit.timeit("a.index(0)", "a=range(10)")0.19335955439601094>>> timeit.timeit("a.index(99)", "a=range(100)")2.1938486138533335