I just discovered in the definition of variables in Python. Namely:
a = b = 0
a = 1
gives me a=1
and b=0
or a and b are two independent variables.
But:
a = b = []
a.append(0)
gives me a = [0]
and b = [0]
, or a and b are two references to the same object. This is confusing to me, how are these two cases different? Is it because int
are primitive types or because lists are just pointers?
a
and b
point to the same object always. But you cannot alter the integer, it is immutable.
In your first example, you rebound a
to point to another object. You did not do that in the other example, you never assigned another object to a
.
Instead, you asked the object a
references to alter itself, to add another entry to that object. All other references to that same object (the list
), will see these changes. That's because list
objects are mutable.
A proper comparison would be to re-assign a
to point to a new list object:
a = b = []
a = [0]
Now you rebound a
and b
is still referencing the first list object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With