python在定义函数时为什么值更改而不使用return

时间:2016-03-28 02:44:04

标签: python

>>> lst=[1]
>>> def f(lst):
        lst[0]=3


>>> f(lst)
>>> lst
[3]

我没有在f中返回,为什么会发生变化?

2 个答案:

答案 0 :(得分:1)

这是因为列表在Python中是可变的,并且您的函数会修改lst。事实上,它与丢失的return声明无关 - 所有这些意味着如果您有x = f(lst)x将是None。如果您想在f上执行lst而不进行变更,请发送副本。这是一个例子:

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]

答案 1 :(得分:0)

这是因为列表的工作方式在python中工作,它不会发送列表中的函数。它将函数发送到已存在列表所在的内存中的位置,然后可以更改

相关问题