在Python中传递列表作为参数

25 投票
4 回答
89347 浏览
提问于 2025-04-15 19:39

如果我运行这段代码:

def function(y):
    y.append('yes')
    return y

example = list()
function(example)
print(example)

为什么它会返回 ['yes'],即使我并没有直接改变变量 'example',我该如何修改代码,让 'example' 不受这个函数的影响呢?

4 个回答

9

“为什么会返回 ['yes']?”

因为你修改了列表 example

“即使我没有直接改变变量 'example'。”

其实你是改变了,你把变量 example 指向的对象传给了函数。这个函数用对象的 append 方法修改了这个对象。

正如在其他地方讨论的那样,append 不会创建新的东西。它是在原地修改对象。

可以查看这些链接了解更多: 为什么 list.append 返回 false?Python 的 append() 和 + 操作符在列表上,为什么结果不同?Python 列表 append 的返回值

“我该如何修改代码,让 'example' 不受函数影响?”

你这是什么意思?如果你不想让 example 被函数更新,那就不要把它传给函数。

如果你希望函数创建一个新的列表,那就让这个函数去创建一个新的列表。

10

修改代码最简单的方法就是在函数调用时加上 [:]。

def function(y):
    y.append('yes')
    return y



example = list()
function(example[:])
print(example)
49

在Python中,所有东西都是引用。如果你想避免这种情况,就需要用list()来创建一个原始列表的新副本。如果这个列表里面还有其他引用,那你就需要使用deepcopy()

def modify(l):
 l.append('HI')
 return l

def preserve(l):
 t = list(l)
 t.append('HI')
 return t

example = list()
modify(example)
print(example)

example = list()
preserve(example)
print(example)

输出结果

['HI']
[]

撰写回答