In this code x = [x for x in range(3)] global x is equal to [0, 1, 2].
The x in the list comprehension is a local variable.
Then let’s define x = [lambda: x for x in range(3)], what will x[0]() return? 0? 2?
No, it will return a list, global x itself.
I want to know why the inner x refers to global x, but not local x?
It’s because of the precedence of operators. Your expression is:
which is equivalent to:
This is a list of three functions, each of which refers to the global x. The lambda creates a scope, and in Python 2, the next scope examined after the local scope is the global scope, so that is where x is found.
This gives you want you want (I think this is what you want):
Here we make use of the fact that default values are evaluated once, in the current scope, when functions are defined. This bakes the value of x into each lambda in the list.