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.
- Why is the id of
c
changing in the first case and not in the second? - Isn't
c+=[5]
equivalent toc=c+[5]
?