We're looking for in-depth reviews and editorials that go beyond the headline. Therefore, it's a good idea to be as detailed as possible and to always link to relevant and original sources. How do I cite?Q:
Why does ::: do nothing in a list comprehension?
In this example:
[1, 2, 3, 4, 5, 6]
::: [5, 4, 3, 2, 1]
It's obvious that the ::: step doesn't do anything, but why is that? Is it due to the fact that 5 is immutable, or that list comprehension doesn't modify the list in place?
A:
As @WiktorStribiżew said, the list comprehension's goal is to take the elements from the iterable (in this case a list), and produce new elements from them. It is lazy, so the elements are evaluated as needed, and don't need to be evaluated first.
The :: step is what allows you to append to an iterable. For example, the following is not valid:
a = [1, 2, 3]
a.append(5)
But this is:
a = [1, 2, 3]
a = a ::: 5
A:
Just looking at the implementation of [5,4,3,2,1], we find that it is just a copy of [5,4,3,2,1]. It doesn't actually add anything to the list.
>>> [5,4,3,2,1]
[5, 4, 3, 2, 1]
>>> [5,4,3,2,1]
[5, 4, 3, 2, 1]
In list comprehension, ::: appends to the left hand side of the assignment. So it doesn't actually do anything to the original list.
>>> a = [1,2,3]
>>> a ::: 4
>>> a
[1, 2, 3, 4]
There is no such thing as immutability in Python. This is a concept from Java.
BALTIMORE (WJZ) — Baltimore city police say a 14-year-old student has been arrested and charged after being accused of pointing a gun at other students.
Police said the incident happened Wednesday afternoon at the Benjamin Guggenheim be359ba680
Related links:
Comments