Python - Arguments and Shared References

Introduction

To illustrate argument-passing properties at work, consider the following code:

Demo

def f(a):  # a is assigned to (references) the passed object 
    a = 99 # Changes local variable a only 
# from   w ww  . j a  va  2s  .co m
b = 88 
f(b)       # a and b both reference same 88 initially 
print(b)   # b is not changed

Result

Here, the variable a is assigned the object 88 when the function is called with f(b).

Changing a inside the function has no effect on the place where the function is called.

It resets the local variable a to a different object.

When arguments are passed mutable objects like lists and dictionaries, in-place changes to such objects may live on after a function exits.

Demo

def changer(a, b):
   a = 2          # from w ww.  j  ava  2s.  c  o m
   b[0] = 'test'  

X = 1 
L = [1, 2]        # Caller: 
changer(X, L)     # Pass immutable and mutable objects 
print( X, L )     # X is unchanged, L is different!

Result

Here, the changer function assigns values to argument a itself, and to a component of the object referenced by argument b.

The parameter assignment in the code above is like the code in the follows.

Demo

X = 1 
a = X               # They share the same object 
a = 2               # Resets 'a' only, 'X' is still 1 
print(X)# w  w  w .  j  a va 2  s . c o m

Result

The assignment through the second argument does affect a variable at the call, though, because it is an in-place object change:

Demo

L = [1, 2] 
b = L               # They share the same object 
b[0] = 'test'       # In-place change: 'L' sees the change too 
print(L)#  w  w w  .j  ava  2  s. c  om

Result

Related Topics

Quiz