What does a list comprehension do
Marko Rauhamaa
marko at pacujo.net
Thu Nov 26 10:36:33 EST 2015
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. 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?
How about:
i = 0
while i < 4:
yield lambda x: i * x
i += 1
or:
for i in range(4):
def f(x):
return i * x
yield f
Marko
More information about the Python-list
mailing list