Read a question on stack overflow sometime back with the following syntax
In [1]: [lambda: x for x in range(5)][0]()
Out[1]: 4
In [2]: [lambda: x for x in range(5)][2]()
Out[2]: 4
But i am having a hard time to understand why exactly the output of this comes as 4,
my understanding is it always gives the last value of the list as output,
In [4]: [lambda: x for x in [1,5,7,3]][0]()
Out[4]: 3
but still not convinced how does this syntax ends up with the last value.
Would be very glad if i can get a proper explanation for this syntax
This isn’t really about either list comprehensions or lambdas. It’s about the scoping rules in Python. Let’s rewrite the list comprehension into an equivalent loop:
Here, we can see that we successively construct functions and store them in a list. When one of these functions is called, all that happens is the value of
xis looked up and returned. Butxis a variable whose value changes, so the final value of4is what is always returned. You could even change the value ofxafter the loop, e.g.,To get the behavior you expected, Python would need to scope the
forcontents as a block; it doesn’t. Usually, this isn’t a problem, and is easy enough to work around.