This question already has an answer here:
- How do I pass a variable by reference? 23 answers
When you pass a collection like list, array to another function in python, does it make a copy of it, or is it just a pointer?
This question already has an answer here:
When you pass a collection like list, array to another function in python, does it make a copy of it, or is it just a pointer?
Answers here have been helpful, but I find the need to exhibit this fine distinction which I haven't seen covered, which I've proven to myself with the subsequent CL experiment:
'num' does not change here because it is an immutable Number object [supports my point 1.]:
'list[0]' here is an immutable Number object also.
So how did 'list[0]', being an immutable Number object, change (supports my point 2.) while the above example's Number object 'num' did not? The immutable Number object 'list[0]' is contained within the mutable list object 'list', while 'num' from the 1st example is just a non-contianed Number object.
Although well-intended, I feel @Stephen Pape top-rated answer (quoted below), and some other similar ones, were not totally correct (and that motivated me to write this answer):
My 2nd code experiment above shows a Number object ('list[0]') being altered within a method, and then the original instance outside the function changed.
Please let me give a humble example
which produces the following result
28329344 var1 28331264 var2 28329344 x 28329344 a 28331264 b After a = b 28331264 a after b = x 28329344 b after return 28329344 var1 28331264 var2 ['1', '2', '3', '4'] ['20', '6', '7', '8', '9']
Mapping to the memory addresses 28329344 28331264 var1 var2 a b x After a=b a After b=x b After a[0] = '20' [0] = '20' After return ['1','2','3','4'] ['20', '6', '7', '8', '9']
I would also recommend looking at the
copy
module:Python documentation for copy
It will help you to understand the underlying issues and how to use it to perform your own deep copy.
A reference is passed, but if the parameter is an immutable object, modifying it within the method will create a new instance.
By reference:
Thing is, the whole reference/value concept won't fit into python. Python has no "value" of a variable. Python has only objects and names that refer to objects.
So when you call a function and put a "name" inside the parenthesis, like this:
The actual object that
myname
is pointing is passed, not the namemyname
itself. Inside the function another name (x
) is given to refer to the same object passed.You can modify the object inside the function if it is mutable, but you can't change what the outside name is pointing to. Just the same that happens when you do
Therefore I can answer your question with:
it is "pass by value" but all values are just references to objects.