Skip to content

Instantly share code, notes, and snippets.

@multidis
Created November 27, 2013 21:26
Show Gist options
  • Save multidis/7683543 to your computer and use it in GitHub Desktop.
Save multidis/7683543 to your computer and use it in GitHub Desktop.
Function calls with mutable objects: Python specifics to keep in mind.
## lists are mutable in python;
## list objects are passed by reference to functions and MAY be changed!
def changer(a,b):
b[0] = 'qq'
a = 2
X = 1
L = [1,2]
changer(X,L)
X,L # tuple: now is (1, ['qq',2])
## mutable object from enclosing scope was modified by a function.
## to avoid modifying mutables by a function:
## COPY object instead of passing by reference!
changer(X, L[:])
## L[:] copies list L to a new object rather than passing the original object by reference.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment