Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...