In the below python code..
Could anyone please let me know why the name(variable) is getting modified if I update the kargs variable in the definition,
def f( kargs):
kargs.extend([10])
print ("In function :",kargs)
name = [1,2,3]
f(name)
print("Outside function :",name)
Output
>>>
In function : [1, 2, 3, 10]
Outside function : [1, 2, 3, 10]
>>>
Python doesn't make a copy of the array when passed into a function, it passes a reference to the same array. More fundamental types would get passed by value instead.
Which then changes name , which is displayed twice.
AFAIK: Python does preserve the value/content of variables among functions of the same file.
So changing it once, will effect all output of name , unless you set it back to its original value, before extending it, using a 2nd variable.
But logically it is going to be wrong if I am not wrong.Is there a way to correct this one.
Logically speaking ... name and kargs are two different variables referring the same namespace.In our case .. since I am extending the local variable inside the function it should be local to the function itself.
In Python the assignment operator `=' never copies data. Whatever is at the left of the `=' is a binding label to a value, not a variable per se. This is significant, since moving labels do not produce another variable.
I recommend you watch Ned Batchelder - Facts and Myths about Python names and values - PyCon 2015 if you are interested on it.
At 15:50 you'll get presentation related to your query, but I would watch it from the beginning since the concept of binding and rebinding labels builds from understanding mutable and immutable values.