Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List modification in a loop

Tags:

python

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)
like image 562
icecrime Avatar asked Mar 28 '12 12:03

icecrime


1 Answers

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 ['_'].

like image 162
MattH Avatar answered Sep 22 '22 12:09

MattH