Why does the behavior of unpacking change when I try to make the destination an array element?
>>> def foobar(): return (1,2)
>>> a,b = foobar()
>>> (a,b)
(1, 2)
>>> a = b = [0, 0] # Make a and b lists
>>> a[0], b[0] = foobar()
>>> (a, b)
([2, 0], [2, 0])
In the first case, I get the behavior I expect. In the second case, both assignments use the last value in the tuple that is returned (i.e. '2'). Why?
When you do a = b = [0, 0]
, you're making both a
and b
point to the same list. Because they are mutable, if you change either, you change both. Use this instead:
a, b = [0, 0], [0, 0]