Created
November 27, 2013 21:26
-
-
Save multidis/7683543 to your computer and use it in GitHub Desktop.
Function calls with mutable objects: Python specifics to keep in mind.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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