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.
c changing in the first case and not in the second?c+=[5] equivalent to c=c+[5]?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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With