Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 899
Elliot Gorokhovsky Avatar asked Jun 07 '26 20:06

Elliot Gorokhovsky


1 Answers

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.

like image 129
shx2 Avatar answered Jun 10 '26 11:06

shx2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!