Created
July 10, 2014 12:55
-
-
Save vilcans/1c598a32be336ada2011 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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