0
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!

Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77
  • How can you tell the difference between `b` referencing `5` and `b` holding a copy of `5`? It's not like `5` is mutable. – melpomene Mar 16 '18 at 20:19
  • because in python 5 is an object and variables don't "store" objects they just "refer" to them. b = 5 means b is neither holding a copy of 5 nor 5 itself rather that b now refers to the object 5. – Fabian Lohrmann Mar 16 '18 at 20:21

1 Answers1

2

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]
Pascal
  • 448
  • 3
  • 11
  • For small enough integers to be automatically interned, there *is* often only a single copy in memory. Which is to say that for the specific example in use, the oversimplification may work. :) – Charles Duffy Mar 16 '18 at 21:30
  • Yes I've heared the same. I was somewhat confused that Pascal said this was a oversimplification. Thanks :) – Fabian Lohrmann Mar 17 '18 at 10:47