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 22:43:17 CET 2014


On 3/24/14 4:03 AM, Ian Kelly wrote:
>
> The difference does not really lie in the lambda construct per se but in
> the binding style of closures. Functional languages tend to go one way
> here; imperative languages tend to go the other. {snip}

> The result may be more surprising to users accustomed to functional
> languages, but I claim that it is *less* surprising to users of other
> imperative languages.

    Aside from the sin of spelling out "lambda,"
       should be   ( \x y -> x + y ) a b )  but, neither here nor there...

    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))
>>>> adders
> [0, 1, 2, 3]
>>>> 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.

    This comes up on the list over and again year after year in various 
flavors, but always because lambda is unnecessarily confusing where it 
comes to how does it function; and by that we mean simply, how does 
scope and closure work in this context. Once the "normal" person is 
introduced to the scope and closure idiosyncrasies of pythons lambda, 
well then everything is much smoother. But how to fix?  Consider:

>>>>
>>>> adders= list(range(4))
>>>> adders
> [0, 1, 2, 3]
>>>> for n in adders:
> 	adders[n] = (lambda b: lambda a: b + a)(n)
>
> 	
>>>> adders[1](3)
> 4
>>>> adders[2](3)
> 5
>>>>

    Now, here is where I talk about confusion; explaining why the first 
lambda above does not work because of scope and closure, and then even 
worse, explaining why the second "double" lambda works in the lower 
example!

    Its a nightmare, really.

    And you are correct, its really about closure.

marcus






More information about the Python-list mailing list