a = 5
a is not holding the value 5 itself but only an address to the object 5, correct? So it is a reference variable.
b = a
Now it seems to me that b
, instead of again holding the address of a
, is actually holding the "value"
of a, which was the address of the object 5. Isn't this the result of Python being pass-by-value?
But how should I understand this apparent discrepancy?
Thanks!
There is no discrepancy.
Think of the assignment a=5
as putting a labelled tag 'a' around 5.
Now if you set b=a
, python looks what is labelled a
(5) and attaches a new label b
to it.
Assignment operators never reference the name of a variable. They always chase the reference down and then reference the chased-down value.
In truth, it doesn't quite work the way I described, because for simple data types such as ints, there isn't just a single copy of the 5 in memory. But you can act as if it worked like that, and won't ever get surprised.
It's easier to understand if you use lists instead of a simple integer:
a = [1, 2, 3]
b = a
There is only a single list in existence, and both a
and b
now reference it, which explains the following.
>>> b[0] = 5
>>> a
[5, 2, 3]