I have this python code
x = [1, 2, 3]
y = x
x += [4]
>>> print(y)
[1, 2, 3, 4]
So, this is because x is y
is True
and if I change x
, I change y
But when I do:
x = [1, 2, 3]
y = x
x = x + [4]
>>> print(y)
[1, 2, 3]
and
>>> id(x) == id(y)
False
I wonder what's the difference. I thought x += 1
is shorthand for x = x+1
but obviously there must be a difference.
I was even more confused, when I tried the above to strings:
name = 'John'
name_2 = name
name += ' Doe'
>>> print(name_2)
'John'
So I think the effect of +=
depends on the object on the left, if it is mutable or not?