What does a list comprehension do
Marko Rauhamaa
marko at pacujo.net
Thu Nov 26 07:56:58 EST 2015
Antoon Pardon <antoon.pardon at rece.vub.ac.be>:
> 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.
Don't go there.
Consider:
q = []
n = 0
x = "hello"
for i in range(4):
def stepper():
global n
n += 1
return i * x
q.append(stepper)
print(n)
print(q[1]())
print(n)
x = "there"
print(q[3]())
print(n)
which prints:
0
hellohellohello
1
theretherethere
2
after your change, you'd get:
0
hello
0
hellohellohello
0
> 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.
I might trip over that one, too. Still, nothing should be changed.
Marko
More information about the Python-list
mailing list