Python: Variable scope for nested generator expression

54 views Asked by At

Can someone explain me the following:

This works as I expect:

>>> [(x, [x for i in xrange(2)]) for x in xrange(3)]
[(0, [0, 0]), (1, [1, 1]), (2, [2, 2])]

Using a generator x is evaluated as 2

>>> [(x, list(x for i in xrange(2))) for x in xrange(3)]
[(0, [2, 2]), (1, [2, 2]), (2, [2, 2])]

This seems because x within the generator expression is taken from the global scope

>>> x = -1
>>> [(x, list(x for i in xrange(2))) for x in xrange(3)]
[(0, [-1, -1]), (1, [-1, -1]), (2, [-1, -1])]
>>> del x
>>> [(x, list(x for i in xrange(2))) for x in xrange(3)]
Traceback (most recent call last):
  File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 4.0.4\helpers\pydev\pydevd_exec.py", line 3, in Exec
exec exp in global_vars, local_vars
  File "<input>", line 1, in <module>
  File "<input>", line 1, in <genexpr>
NameError: global name 'x' is not defined

Why is that?

0

There are 0 answers