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?

1
  • The behaviour of unpacking doesnt change, you are doing a multiple assignment in the 2nd example, not unpacking Commented Apr 18, 2013 at 3:13

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, Volatility, for the suggestion.
2

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.