[issue14845] list(<generator expression>) != [<list comprehension>]

Peter Norvig report at bugs.python.org
Fri May 18 00:47:37 CEST 2012


New submission from Peter Norvig <pnorvig at google.com>:

PEP 289 says "the semantic definition of a list comprehension in Python 3.0 will be equivalent to list(<generator expression>).  Here is a counterexample where they differ (tested in 3.2):

def five(x):
    "Generator yields the object x five times."
    for _ in range(5):
        yield x


# If we ask five() for 10 objects in a list comprehension,
# we get an error:

>>> F = five('x')
>>> [next(F) for _ in range(10)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

# But if we ask five() for 10 objects in a list(generator expr),
# we get five objects, no  error:

>>> F = five('x')
>>> list(next(F) for _ in range(10))
['x', 'x', 'x', 'x', 'x']

----------
components: None
messages: 161023
nosy: Peter.Norvig
priority: normal
severity: normal
status: open
title: list(<generator expression>) != [<list comprehension>]
type: behavior
versions: Python 3.2

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue14845>
_______________________________________


More information about the Python-bugs-list mailing list