+ 2

Reassigning value in python

Actually, i wrote a code like this- #code1 l=[1,2,3] print(id(l)) l+=[5] print(id(l)) #code2 l=[1,2,3] print(id(l)) l=l+[5] print(id(l)) Before, i thought that both the codes should have done the same thing, but the id in tge first case changes but remains the same in the second case. Has it something to do with reassignment or what? Please someone explain in detail.

13th Nov 2018, 12:59 PM
Pulkit Kamboj
Pulkit Kamboj - avatar
1 Réponse
+ 10
Actually, the id remains the same in the first case, but changes in the second. The += uses the in-place __iadd__() operator (when available), which in case of lists is just the extend() method. It doesn't change the address of the list (hence the name "in-place"), just adds the elements from the other list at the end. It's more efficient. l = l + [5] makes a NEW list by joining the original l and [5], and then gives it the name l. The address of the new list is naturally not the same as the old one.
13th Nov 2018, 1:29 PM
Kishalaya Saha
Kishalaya Saha - avatar