>>> lst=[1]
>>> def f(lst):
lst[0]=3
>>> f(lst)
>>> lst
[3]
我没有在f中返回lst,为什么lst改变?python在定义函数时为什么值改变而不使用return
>>> lst=[1]
>>> def f(lst):
lst[0]=3
>>> f(lst)
>>> lst
[3]
我没有在f中返回lst,为什么lst改变?python在定义函数时为什么值改变而不使用return
这是因为方式列表工作在Python中,它不会发送函数列表。它将函数发送到已存在列表所在的内存中,然后可以更改它
这是因为列表在Python中是可变的,并且您的函数修改了lst
。事实上,它与缺失的return
声明无关 - 所有这一切意味着如果您有x = f(lst)
,x
将是None
。如果您想在lst
上执行f
而不改变它,请发送副本。这里有一个例子:
lst = [1, 2, 3]
def fn(lst):
print("in fn")
lst[1] = 10
x = lst[::] # make a copy
print("X before is:", x)
fn(x)
print("X after is:", x)
print("Lst after calling fn with x but before using Lst is:", lst)
fn(lst)
print("Lst after is:", lst)
此打印:
X before is: [1, 2, 3]
in fn
X after is: [1, 10, 3]
Lst after calling fn with x but before using Lst is: [1, 2, 3]
in fn
Lst after is: [1, 10, 3]
列表是可变的 – Bahrom