Explanation of this Python language feature? [x for x in x for x in x] (to flatten a nested list)
Ian Kelly
ian.g.kelly at gmail.com
Sat Mar 22 05:09:56 EDT 2014
On Fri, Mar 21, 2014 at 8:06 PM, Rustom Mody <rustompmody at gmail.com> wrote:
> Two: A comprehension variable is not bound but reassigned across the
> comprehension. This problem remains in python3 and causes weird behavior when
> lambdas are put in a comprehension
Because Python as a language only has the concept of assignment, not
binding. I think it would be weird and confusing if variables worked
this way in comprehensions and nowhere else.
> >>> fl = [lambda y : x+y for x in [1,2,3]]
> >>> [fl[i](2) for i in [0,1,2]]
> [5, 5, 5]
You can get the desired effect by adding a layer of indirection:
>>> fl = [(lambda x: lambda y: x+y)(x) for x in [1,2,3]]
>>> [f(2) for f in fl]
[3, 4, 5]
If that's too ugly then give the wrapper a proper name:
>>> def make_function(x):
... return lambda y: x+y
...
>>> fl = [make_function(x) for x in [1,2,3]]
>>> [f(2) for f in fl]
[3, 4, 5]
There is also the default argument trick:
>>> fl = [lambda y, *, x=x: x+y for x in [1,2,3]]
>>> [f(2) for f in fl]
[3, 4, 5]
More information about the Python-list
mailing list