-1

Much has been written about python pass-by-object-reference. But it is confusing to read threads like this or this.

In those threads, some say mutability is important, while others say that mutable or immutable objects are handled the same way.

I have a simple question, why are the contents of a not modified in the first snippet of code and modified in the second? According to this explanation of pass-by-object-reference, shouldn't the contents of the reference be modified in both cases?

def fn(b):
    b += 1
a = 2
fn(a)
print(a)

def fn(b):
     b += [4]
a = [2]
fn(a)
print(a)
Community
  • 1
  • 1
Ricardo Magalhães Cruz
  • 3,504
  • 6
  • 33
  • 57
  • The posts (not threads; SO is not a forum) that you link to contain huge amounts of information. Please read through the available answers instead of asking us to reprint them. – TigerhawkT3 Aug 24 '16 at 06:37
  • Technically, Python uses "[call by sharing](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing)," an obscure term. Also, your confusion really stems from a fundamental misunderstanding of Python variables. Variables in Python are like name tags that we place on objects. When we pass an an argument to a function, we put the name tag given by the parameter on that object. – juanpa.arrivillaga Aug 24 '16 at 08:28

1 Answers1

0

shouldn't the contents of the reference be modified in both cases?

No, since int objects are immutable.

You don't even need functions to demonstrate this.

Consider the following:

a = 1
print(id(a))
a += 1
print(id(a))
>> 496418832
   496418848

We are obviously getting a new object.

Compare to:

a = [1]
print(id(a))
a += [2]
print(id(a))
>> 36641608
   36641608

Note a is still referencing the same object in this case.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154