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:44:37 EDT 2014
On 3/24/14 6:01 PM, Chris Angelico wrote:
> Easy fix. Use the "explicit capture" notation:
> adders[n] = lambda a, n=n: a+n
> And there you are, out of your difficulty at once!
Yes, yes, yes, and example:
>>>> adders= list(range(4))
>>>> for n in adders:
> adders[n] = lambda a, n=n: a+n
>
>
>>>> adders[1](3)
>4
>>>> adders[2](3)
>5
But, and this is the big (WHY?) is that necessary? In other words,
its not about experts knowing how to make this work, its about "normal"
people not understanding in the first place why its a problem, and why
the various solutions work to fix it; even though "we" all know that
nothing is 'broken'.
And in reference to Marko's post, he's right, its not just python,
but the issue is not where else is capture and scope a problem for
confusion, the issue is whether python's lambda provides a significant
opportunity for confusion that in the larger scheme of things (no pun
intended) is not warranted.
marcus
More information about the Python-list
mailing list