Suppose I have this function
>>>a=3
>>>def num(a):
a=5
return a
>>>num(a)
5
>>>a
3
Value of a doesnt change.
Now consider this code :
>>> index = [1]
>>> def change(a):
a.append(2)
return a
>>> change(index)
>>> index
>>> [1,2]
In this code the value of index changes. Could somebody please explain what is happening in these two codes. As per first code, the value of index shouldnt change(ie should remain index=[1]).
You need to understand how python names work. There is a good explanation here, and you can click here for an animation of your case.
If you actually want to operate on a separate list in your function, you need to make a new one, for instance by using
a = a[:]
before anything else. Note that this will only make a new list, but the elements will still be the same.
The value of index doesn't change. index still points to the same object it did before. However, the state of the object index points to has changed. That's just how mutable state works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With