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.
第一个代码块中的第3行是赋值 ,第二个块中的第3行是变异 ,这就是您观察该行为的原因。
The issue you are encountering is:
a = 3
def num(a):
# `a` is a reference to the argument passed, here 3.
a = 5
# Changed the reference to point at 5, and return the reference.
return a
num(a)
The a
in the num
function is a diffrent object than the a
defined globally. It works in case of the list because a
points at the list passed, and you modify the object being referenced to by the variable, not the reference variable itself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.