10

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)
4
  • 3
    and for completeness, the "correct" way to do this is [x+1 for x in L] Commented Mar 28, 2012 at 12:17
  • @Kimvais: that assumes you want to create a new list. Commented Mar 28, 2012 at 12:26
  • 1
    L = [x+1 for x in L] if you don't want a new list, then :) Commented Mar 28, 2012 at 12:28
  • 1
    @Kimvais: That still creates a new list, it's just setting L to refer to the new list. Commented Mar 28, 2012 at 12:45

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.