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

Chris Angelico rosuav at gmail.com
Tue Mar 25 00:57:34 CET 2014

On Tue, Mar 25, 2014 at 10:44 AM, Mark H Harris <harrismh777 at gmail.com> wrote:
> 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!
>    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'.

Why is it necessary? For the same reason that this works:

def func_pair():
    x = 0
    def inc():
        nonlocal x; x+=1
        return x
    def dec():
        nonlocal x; x-=1
        return x
    return inc, dec

fooup, foodn = func_pair()
barup, bardn = func_pair()
>>> fooup(), fooup(), fooup(), foodn()
(1, 2, 3, 2)
>>> barup(), barup(), bardn(), bardn()
(1, 2, 1, 0)

When you use the variable x in multiple places, it's the same variable
and it has a single value. If you don't want that, you have to make a
separate variable.


More information about the Python-list mailing list