Python - Avoiding Mutable Argument Changes

Introduction

For function arguments, we can copy the list at the point of call:

Demo

def changer(a, b):
   a = 2          #  w  w  w . j  a  v a2 s .com
   b[0] = 'test'  
X = 1 
L = [1, 2] 
changer(X, L[:])        # Pass a copy, so our 'L' does not change 

print( X, L )

Result

We can copy within the function itself, if we never want to change passed-in objects, regardless of how the function is called:

Demo

def changer(a, b): 
    b = b[:]            # Copy input list so we don't impact caller 
    a = 2 #   w ww.  ja  va 2 s . c  o m
    b[0] = 'test'       # Changes our list copy only 

X = 1 
L = [1, 2] 
changer(X, L[:])        # Pass a copy, so our 'L' does not change 
print( X, L )

Result

Related Topic