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

Mark H Harris harrismh777 at gmail.com
Mon Mar 24 19:56:23 EDT 2014


On 3/24/14 5:43 PM, Marko Rauhamaa wrote:
> Mark H Harris<harrismh777 at gmail.com>:

>>     Yes, its about closures, totally;  the most confusing aspect of
>> lambda in python is not only the syntax but the idea of scope and
>> closure (for that syntax).  Everyone is confused by this initially, not
>> because its complicated, but because its confusing.  An example:

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

>>     The expected value as perceived by "normal" people is 4.
>
> 1. No, I don't think that understanding is automatically natural.

    It might not seem that way for an expert, but if you Google python 
lambda function closure(s)  you will notice that this is pretty much the 
natural way of interpreting things.

    Of course the problem is that the closure grabs the *last* number in 
the list which is used for each of the adder[] functions created. So, in 
other words, three (3) is the number added in each of the adder 
functions.  But here is the rub, it is not *ever* clear to people (even 
experienced python coders, me for instance) that this is how it should 
work. What is needed is the explicit closure "grab" recommended by 
ChrisA. But for the normal, that is just as bad (conceptually) because 
while it works it strays FAR away from expected lambda constructs known 
to functional programmers, and it is difficult to explain to non 
functional programmers... a proverbial catch 22.

marcus



More information about the Python-list mailing list