Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vilcans/1c598a32be336ada2011 to your computer and use it in GitHub Desktop.
Save vilcans/1c598a32be336ada2011 to your computer and use it in GitHub Desktop.
"""
TL;DR for http://www.librador.com/2014/07/10/Variable-scope-in-list-comprehension-vs-generator-expression/
In Python 2, a list comprehension "leaks" its variable into the current scope,
while a generator expression does not.
This means that there's a subtle difference between
`list(x for x in y)` and `[x for x in y]`.
Example:
>>> [a for a in (1, 2, 3)]
[1, 2, 3]
>>> a
3
>>> list(b for b in (1, 2, 3))
[1, 2, 3]
>>> b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
In Python 3, the variable doesn't leak in list comprehensions either.
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment