You would like to google "python pass by assignment" for example.
When you pass an argument to a function, the passed object is assigned to the internal variable of the function. For example, in
def myFun(x):
for i in range(len(x)):
x[i] += 2
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
you are first bounding a name lst
to an object [10, 11, ..., 15]
(outside the function). Then you pass this to the function, so that inside the function, x
refers to the same object which lst
was refering to. So you have two names (lst
outside the function and x
inside the function) for the same object. When the function does x[i] += 2
, it goes to this object (i.e., the list) and does the work. It does not care whether it is called x
or lst
; it just increment the i-th element of that specific object. Since x
and lst
are just different names of the object, after the function call, lst
refers to that (modified) object. x
is not available outside the function; it is just discarded. But you still have the name lst
, which still points to the (modified) object.
Now in
def myFun(x):
x = [20, 30, 40]
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
The procedure is the same; x
first refers to the object lst
was refering to: the object [10, ..., 15]
. But then you say "now x
, listen to me. Don't point to that object. You now refer to a newly created list [20, 30, 40]
." This is what the assignment x = ...
does. Now x
and lst
points to totally different objects. As above, x
is discarded, and so is the object it refered to. lst
still points to the object it has been pointing, which was not modified by the function.