To illustrate argument-passing properties at work, consider the following code:
def f(a): # a is assigned to (references) the passed object a = 99 # Changes local variable a only # from w w w. j a v a 2s . c o m b = 88 f(b) # a and b both reference same 88 initially print(b) # b is not changed
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.
def changer(a, b): a = 2 # from ww w.j av a 2s .c o m b = 'test' X = 1 L = [1, 2] # Caller: changer(X, L) # Pass immutable and mutable objects print( X, L ) # X is unchanged, L is different!
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.
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 v a 2 s. co m
The assignment through the second argument does affect a variable at the call, though, because it is an in-place object change:
L = [1, 2] b = L # They share the same object b = 'test' # In-place change: 'L' sees the change too print(L)# from w w w . j a v a 2s. co m