ls = [1,2,3]
id(ls)
output: 4448249184 # (a)
ls += [4]
id(ls)
output: 4448249184 # (b)
ls = ls + [4]
id(ls)
output: 4448208584 # (c)
Why are (a) and (b) the same, but (b) and (c) are different?
Isn't L += x the same as L = L + x?
ls = [1,2,3]
id(ls)
output: 4448249184 # (a)
ls += [4]
id(ls)
output: 4448249184 # (b)
ls = ls + [4]
id(ls)
output: 4448208584 # (c)
Why are (a) and (b) the same, but (b) and (c) are different?
Isn't L += x the same as L = L + x?
Using +=, you are modifying the list in plac, like when you use a class method that append x to L (like .append, .extend…). This is the __iadd__ method.
These methods are called to implement the augmented arithmetic assignments (+=, -=, *=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self).
Using L = L + x, you are creating a new list (L+x) that you are affecting to a variable (in this case L).
Augmented assignment in List case is different. it is not actual assignment like in integer so that
a += b
is equal to
a = a+b
while in case of List it operate like:
list += x
is:
list.extends(x)