I am new to Python and I am trying to understand when we can modify a variable used in a function.
In the example below, the object bound to x
is not modified by f
as we can see in the output. I don't understand why.
From my understanding, when we do x.append(4)
in f
, we modify the object bound to the name x
. But it seems that it is not the case, given the output. Where is my error?:
Am i missing something with global variables vs local variables?
Is there a copy of the object which is done when we call f
?
My question is similar to this question. However the conclusion was not clear for me and it didn't help me to understand where I was wrong.
def f(x):
x = [0,1,2,3]
x.append(4)
print('In f():', x)
x = [0,1,2,3]
print('Before:', x)
f(x)
print('After :', x)
Output
Before: [0, 1, 2, 3]
In f(): [0, 1, 2, 3, 4]
After : [0, 1, 2, 3]