What does a list comprehension do

Antoon Pardon antoon.pardon at rece.vub.ac.be
Thu Nov 26 06:52:45 EST 2015


Op 26-11-15 om 12:13 schreef Nobody:
> Returning to the original expression:
>
> 	> q = [lambda x: i * x for i in range(4)]
> 	> q[0](1), q[3](1)
> 	(3, 3)
> 	> q = [lambda x,i=i: i * x for i in range(4)]
> 	> q[0](1), q[3](1)
> 	(0, 3)

Personnaly I would prefer:

>>> q = [(lambda i: lambda x: i * x)(i) for i in range(4)]
>>> q[0](1), q[3](1)
(0, 3)

And this is where I ask whether it would be worth the effort to change
the behaviour of python.

In general the following two seem equivallent:

   [<expression> for x in <iter>] and [(lambda x: <expression>)(x) for x in <iter>]

The only exceptions seems to be when <expression> is itself a lambda.

It also seems that people who try this for the first time are surprised
with what they get and seem to expect there list comprehension to
act as if they had written the second version.

So would it be advisable if python would translate the expression people
write into a lambda that gets called?

Are there issues that could come up?




More information about the Python-list mailing list