3

In the process of understanding mutability and immutability concepts, I was trying out different things and came across this:

When I wrote a simple code shown below (I will refer to this as code 1):


c=[1,2,3]
print(id(c))
c=c+[5]
print(c)
print(id(c))

The output is this:

1911612356928
[1, 2, 3, 5]
1911611886272

And when I wrote the code (I will refer to this as code 2):


c=[1,2,3]
print(id(c))
c+=[5]
print(c)
print(id(c))

The output is this:

1911612356928
[1, 2, 3, 5]
1911612356928

As c is a list which is mutable in python, I expected the ID to remain the same in code 1 and was confused by the output. Changing the syntax from c+=[5] to c=c+[5] in code gave me a different output where the ID of c did not change though I am performing the same operation on c as in code 1.

  1. Why is the id of c changing in the first case and not in the second?
  2. Isn't c+=[5] equivalent to c=c+[5]?
jottbe
  • 4,228
  • 1
  • 15
  • 31
RSG
  • 41
  • 2
  • 1
    Take a look at this: https://stackoverflow.com/questions/9766387/different-behaviour-for-list-iadd-and-list-add , but that link doesn't explain why they chose to design it this way. I haven't watched it yet, but someone posted this link as a comment on that answer suggesting it might explain the reasoning behind this design choice: https://pyvideo.org/pycon-us-2012/python-epiphanies.html. Also read this paragraph https://docs.python.org/3/reference/datamodel.html#object.__ior__ which explains that the inplace methods should return `self` where they can. – Dan Oct 03 '20 at 18:58
  • 1
    Because `c += [5]` adds a new element to the same list, the other concattenates two list and assigns the (changed) result back to the name of one of those 2 lists - but the `c+[5]` is still a new list thats assigned to be known as `c` for then on – Patrick Artner Oct 03 '20 at 18:59

1 Answers1

2

c += 5 and c = c + [5] produce the same value of c, but the implementation is slightly different.

c += 5 is a single statement that is implemented by effectively appending 5to c. That is, the existing c list is extended in-place; its id does not change.

c = c + [5] contains two statements. The first one is c + [5], which creates a new list (distinct from the original c). The second is the assignment, which assigns the right operand (the new list created by the c + [5] expression) to the name c. Since c has been reassigned to point to a new list, its id is now different.

Another way to look at it is that c = c + [5] is the same as:

temp = c + [5]
c = temp
Samwise
  • 68,105
  • 3
  • 30
  • 44