What does a list comprehension do

Antoon Pardon antoon.pardon at rece.vub.ac.be
Thu Nov 26 14:18:14 EST 2015


Op 26-11-15 om 16:36 schreef Marko Rauhamaa:
> Antoon Pardon <antoon.pardon at rece.vub.ac.be>:
> 
>>     [ <expression> for <var> in <iter> ]
>>
>> would implicitly be rewritten as follows:
>>
>>     [ (lambda <var>: <expression>)(<var>) for <var> in <iter>]
> 
> Funny enough, that's how "list comprehensions" are created in Scheme:
> 
>    (map (lambda (i)
>           (lambda (x) (* i x)))
>         '(0 1 2 3))))
> 
>> There would no change on how lambdas work or functions or closures.
> 
> First of all, it's weird to spend any effort in trying to alter a very
> special case.

<shrug> Maybe it is small enough an effort but I wont loose any sleep over it
should the dev team have other priorities.

> I don't recall having to generate a list of such
> functions. In fact, I barely ever use lambda in Python; explicit def
> statements are much more pleasing to the eye and are not restricted to
> simple expressions.
> 
> Secondly, you'd lose the nice symmetry between for statements and
> comprehensions/generators. For example:
> 
>    ( lambda x: i * x for i in range(4) )
> 
> corresponds to:
> 
>     for i in range(4):
>         yield lambda x: i * x
> 
> Would you embed an extra lambda there, too?

No, not because that would be so troublesome in semantics
but because it would be annoying in python. Because in that
case you would embed a function (call) or introduce an
intermediate scope. Which would mean that if you want
to rebind a variable within the suite of the for loop
that is also used in other parts of the function/modules
you would have to declare that variable nonlocal/global at the
start of the suite. So it would be annoying plus that
it would be difficult to explain to people new to the
language.

Such an embedding would only be practical in a language where
you have to declare your variables.

-- 
Antoon.



More information about the Python-list mailing list