I'm a newcomer to Python but I understand that things should not be done this way, so please consider the following code snippets as purely educational :-)
I'm currently reading 'Learning Python' and trying to fully understand the following example:
>>> L = [1, 2, 3, 4, 5]
>>> for x in L:
... x += 1
...
>>> L
[1, 2, 3, 4, 5]
I did not understand if this behavior was somewhat related to the immutability of the numeric types, so I've run the following test:
>>> L = [[1], [2], [3], [4], [5]]
>>> for x in L:
... x += ['_']
...
>>> L
[[1, '_'], [2, '_'], [3, '_'], [4, '_'], [5, '_']]
Question: what makes the list unchanged in the first code and changed in the second ?
My intuition is that the syntax is misleading and that:
x += 1
for an integer really means x = x + 1
(thus assigning a new reference)x += ['_']
for a list really means x.extend('_')
(thus changing the list in place)Question: what makes the list unchanged in the first code and changed in the second ?
In the first code, the list is a sequence of (immutable) integers. The loop sets x
to refer to each element of the sequence in turn. x += 1
changes x
to refer to a different integer that is one more than the value x
previously referred to. The element in the original list is unchanged.
In the second code, the list if a sequence of (mutable) lists. The loop sets x
to refer to each element of the sequence in turn. x += ['_']
as x
refers to a list, this extends the list referred to by x
with ['_']
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With