What does a list comprehension do

Antoon Pardon antoon.pardon at rece.vub.ac.be
Thu Nov 26 08:33:59 EST 2015


Op 26-11-15 om 13:56 schreef Marko Rauhamaa:
> 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

I don't understand. What I propose would be a minor change in
how list comprehension works. I don't see how your example
can be turned into a list comprehension. I can of course
put the stepper function out of the for loop and then
convert the for loop into a list comprehension.

The results in that case is that my proposed change wouldn't
effect the results in python2 and that the code wouldn't run
in python3.

So could you clarify what list comprehension you are talking
about, that you think would cause trouble, should my proposal
be adopted.
-- 
Antoon.




More information about the Python-list mailing list