Default value for next element in Python iterator if iterator is empty?

next accepts a default value:

next(...)
    next(iterator[, default])

    Return the next item from the iterator. If default is given and the iterator
    is exhausted, it is returned instead of raising StopIteration.

and so

>>> print next(i for i in range(10) if i**2 == 9)
3
>>> print next(i for i in range(10) if i**2 == 17)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> print next((i for i in range(10) if i**2 == 17), None)
None

Note that you have to wrap the genexp in the extra parentheses for syntactic reasons, otherwise:

>>> print next(i for i in range(10) if i**2 == 17, None)
  File "<stdin>", line 1
SyntaxError: Generator expression must be parenthesized if not sole argument

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)