According to the list comprehension doc and this question: squares = [x**2 for x in range(10)]
is equivalent to squares = list(map(lambda x: x**2, range(10)))
But does Python actually implement list comprehension via map
and lambda
? Or is the squares = list(map(lambda x: x**2, range(10)))
in the document just an approximation instead of exactly equivalence?
If so, how to deal with iterating an
enumerate
object? For example,squares = [(idx, x**2) for idx, x in enumerate(range(10))]
? I find it hard for me to imitate the previous example and re-write it usingmap
andlambda
.If not(I tend to this option but not sure), is the list comprehension is implemented separately? Is there anything python sentence that is exactly equivalent to the list comprehension?
My research effort:
I tried squares = [print(locals()) for x in range(1)]
vs squares = list(map(lambda x: print(locals()), range(1)))
, inspried by this question eval fails in list comprehension. The first one will give {'.0': <range_iterator object at 0x000002AB976C4430>, 'x': 0}
while the latter gives {'x': 0}
. Perhaps this indicates that they are not exactly equivalence.
I also found these question:
- Where are list comprehensions implemented in CPython source code?
- How does List Comprehension exactly work in Python?
- List comprehension vs map
They are using Python assembly to show the behavior of list comprehension. These answers perhaps indicate that the list comprehension is implemented separately.
So I tend to believe that the list comprehension is not implemented by map
and lambda
. However, I am not sure, and want to know "is there anything python sentence that is exactly equivalent to the list comprehension" as I mentioned above.
The origin of this question:
I am trying to answer a question. I want to explain strange behaviors related to the list comprehension without using python assembly. I used to think the list comprehension is implemented via lambda
in my previous answer. However, I am doubting about this now.