I've noticed a (seemingly) strange behaviour with assignments, which has led me several times to do programming mistakes.
See the following example first :
>>> i = 0
>>> t = (i,)
>>> t
(0,)
>>> i += 1
>>> t
(0,)
As expected, the value of the unique element of t
does not change, even after the value of i
has been incremented.
See now the following :
>>> l = [0]
>>> t = (l,)
>>> t
([0],)
>>> l[0] += 1
>>> t
([1],) # <- ?
I don't understand why the initial zero in t
is now one ; if I had incremented it with a reference to t
...
>>> t[0][0] += 1
... I'd understand that it's value has changed, but this is not the case in the preceding example, where only l
is explicitly referenced when incrementing.
I've got two questions:
- Why is it so?
- Are there special rules I should be aware of concerning this?