Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
919 views
in Technique[技术] by (71.8m points)

list - Python multiple assignment and references

Why does multiple assignment make distinct references for ints, but not lists or other objects?

>>> a = b = 1
>>> a += 1
>>> a is b
>>>     False
>>> a = b = [1]
>>> a.append(1)
>>> a is b
>>>     True
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In the int example, you first assign the same object to both a and b, but then reassign a with another object (the result of a+1). a now refers to a different object.

In the list example, you assign the same object to both a and b, but then you don't do anything to change that. append only changes the interal state of the list object, not its identity. Thus they remain the same.

If you replace a.append(1) with a = a + [1], you end up with different object, because, again, you assign a new object (the result of a+[1]) to a.

Note that a+=[1] will behave differently, but that's a whole other question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...