Explanation of this Python language feature? [x for x in x for x in x] (to flatten a nested list)

Terry Reedy tjreedy at udel.edu
Mon Mar 24 21:20:48 EDT 2014


On 3/24/2014 7:56 PM, Mark H Harris wrote:

>     Of course the problem is that the closure

A function is not a closure unless defined within another function. In 
the examples I remember, there was no nesting.

 > grabs the *last* number in
> the list which is used for each of the adder[] functions created.

Wrong. Functions look up global and nonlocal names, such as n, when the 
function is called.

 >>> adders = list(range(4))
 >>> for n in adders: adders[n] = lambda a: a+n

 >>> n = 1000
 >>> adders[1](3)
1003

Same result if the function *is* a closure, making n nonlocal rather 
than global.

def f():
     adders = list(range(4))
     for n in adders: adders[n] = lambda a: a+n
     n = 1000
     return adders

print(f()[1](3))
 >>>
1003

The only definition time grabbing is with default arg expressions.

This discussion is a bit funny in a way. Some people are puzzled that 
default arg expressions 'grab' just once, as definition time, rather 
than with each call. Others (I hope others) are puzzled that body 
expressions 'grab' with each call, rather than just once, at definition 
time. That seems to be particularly true when the body is in a lambda 
expression rather than a def statement.

-- 
Terry Jan Reedy




More information about the Python-list mailing list