0

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?

Gordon Bean
  • 4,272
  • 1
  • 32
  • 47
  • The behaviour of unpacking doesnt change, you are doing a multiple assignment in the 2nd example, not unpacking – jamylak Apr 18 '13 at 03:13

2 Answers2

3

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]
Volatility
  • 31,232
  • 10
  • 80
  • 89
2

a = b = [0, 0] # Makes a and b the same list

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • gnibbler, you beat me too it. :) I just realized my folly and returned to delete the question, and you had already answered. Thank you for the prompt reply. – Gordon Bean Apr 18 '13 at 02:59