[Python-Dev] Seeming unintended difference between list comprehensions and generator expressions... (original) (raw)

Carl Johnson cmjohnson.mailinglist at gmail.com
Sun Feb 22 09:17:02 CET 2009


Nick Coghlan wrote:

Josiah Carlson wrote: >> Similarly, a 3.x list comprehension [i*i for i in x] is very roughly >> translated as: >> >> def lc(arg): >> result = [] >> for i in arg: >> result.append(i*i) >> return result >> >> = lc(x) > > I was under the impression that in 3.x, it was equivalent to > list() . Which would explain the difference between 2.6 and > 3.0. Semantically, the two translations end up being the same.

Actually, they're not quite the same. list() will swallow any StopIteration exceptions that end up getting thrown inside the generator, but even in Python 3, list comprehensions will not catch StopIteration. So for explanatory purposes, thinking of a list comprehension as a function that returns a list is more useful than thinking of it as list().

-- Carl



More information about the Python-Dev mailing list