What does a list comprehension do

dieter dieter at handshake.de
Thu Nov 26 02:17:43 EST 2015


Antoon Pardon <antoon.pardon at rece.vub.ac.be> writes:

> Op 20-11-15 om 08:49 schreef dieter:
>> In addition, the last few days have had two discussions in this list
>> demonstrating the conceptial difficulties of late binding -- one of them:
>>
>>       Why does "[lambda x: i * x for i in range(4)]" gives
>>       a list of essentially the same functions?
>
> Can you (or someone else) explain what a list comprehension is equivallent of.
> Especially in python3.

I am not sure about "Python3" (never used it), but in Python 2,
the simple list comprehension "[x for x in l]" is roughly equivalent to:

    result = []
    for x in l: result.append(x)
    ... the list comprehension result is in "result" which (however) is not bound ...

In Python 3, "x" might not be bound as well - to harmonise list comprehension
with generator expressions (and avoid the confusion, that a local
(temporary) binding can change the value of a global binding).




More information about the Python-list mailing list