def A(x):
x = 10
print (x)
a= 2
A(a) # 10
print(a) # 2 a is still referring to the same object
def B(x):
x[0] = 1
print (x)
b = [0,0,0,0,0]
B(b) # [1, 0, 0, 0, 0]
print (b) # [1, 0, 0, 0, 0] b changed!
Passing Immutable Objects
We have the variable a
referring to the object with value 2
.
When we pass a
to A(x)
, the function has the local variable x
referenced to the same object.
Since integer is immutable, by definition we are not able to modify the objects value to 10 in place, all the time, the variable a continues to refer to the object with the value 2, what explains why the value of a doesnt not change after calling.
NOTE: we can still "modify" immutable objects by capturing the return of the function.
def A(x):
x = 10
return (x)
a= 2
a = A(a)
print(a) # 10 a now refers to the new object created by the function
By assigning the return
value of the function to a, we have reassigned a to refer to the new object with the value 10 created in the function. Note the object a initially referred to never change — it is still 2 — but by having a point to a new object created by the function, we are able to “modify” the value of a.
Passing Mutable Objects
The B(b)
function generates a different result when we passing a mutable object.
The code b = [0,0,0,0,0]
has the variable b
refer to the list object containing references to three immutable objects: integer 0, 0, 0, 0 and 0.
As usual, when we pass b
to B()
, the function has the local variable x
refer to the same object as b
.
The x[0] = 1
modifies the list in place, since list is mutable.
Since no new object is created and the change occurred in place of the object, when we print b, we get the modified list.