Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Id of list is changing when I use list=list+something but not changing when I use list+=something (in Python)

Tags:

python

list

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]?
like image 770
RSG Avatar asked Oct 31 '25 09:10

RSG


1 Answers

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
like image 136
Samwise Avatar answered Nov 02 '25 22:11

Samwise