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

Marko Rauhamaa marko at pacujo.net
Sat Mar 22 06:24:47 EDT 2014


Steven D'Aprano <steve+comp.lang.python at pearwood.info>:

> This makes perfect sense: by the time you call the functions, the name x 
> has been rebound to the value 3.

> [...]

> Now I'm not sure precisely how Haskell implements this trick, but it
> suggests to me that it creates a different closure each time around
> the loop of the comprehension. That could end up being very expensive.

Haskell does not rebind variables. I guess Haskell simply physically
substitutes object references for each syntactic occurrence of a
variable.

If Python worked analogously, the following loop:

   for i, x in enumerate([1, 2, 3]):
       f[i] = lambda y: x + y

would unroll as follows:

   f[0] = lambda y: 1 + y
   f[1] = lambda y: 2 + y
   f[2] = lambda y: 3 + y

That is actually how classic lambda calculus does it. Variables are
substituted, not "bound" or "assigned". They are syntactic slots. There
is no heap, there is no stack, there is no memory apart from the
expression itself.


Marko



More information about the Python-list mailing list