Ran into this issue when debugging a piece of code. If was not aware of this behaviour previously.
foo = bar = [1, 2, 3]
hex(id(foo))
Out[121]: '0x1f315dafe48'
hex(id(bar))
Out[122]: '0x1f315dafe48'
Both "variables" are pointing to the same memory location. But now if one is changed, the other changes as well:
foo.append(4)
bar
Out[126]: [1, 2, 3, 4]
So essentially here we have two names assigned to the same variable/memory address. This is different from:
foo = [1, 2, 3]
bar = [1, 2 ,3]
hex(id(foo))
Out[129]: '0x1f315198448'
hex(id(bar))
Out[130]: '0x1f319567dc8'
Here a change to either foo
or bar
won't have any effect on the other one.
So my question is: why does this feature (chained assignment for mutable types) even exist in Python? Does it serve any purpose apart from giving you tools to shoot yourself in the foot?