문제

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]

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top