Dangerous behavior of list(generator)

Peter Otten __peter__ at web.de
Thu Dec 31 04:54:59 EST 2009


Tom Machinski wrote:

> It would be nice if there was a builtin for "get the first element in
> a genexp, or raise an exception (which isn't StopIteration)", sort of
> like:
> 
>   from itertools import islice
> 
>   def first_or_raise(genexp):
>       L = list(islice(genexp, 1))
>       if not L:
>           raise RuntimeError('no elements found')
>       return L[0]

Somewhat related in 2.6 there's the next() built-in which accepts a default 
value. You can provide a sentinel and test for that instead of using 
try...except:

>>> from random import randrange
>>> from functools import partial
>>> def g():
...     return iter(partial(randrange, 3), 2)
...
>>> next(g(), "empty")
1
>>> next(g(), "empty")
1
>>> next(g(), "empty")
'empty'
>>> next(g(), "empty")
'empty'
>>> next(g(), "empty")
'empty'
>>> next(g(), "empty")
0

Peter



More information about the Python-list mailing list