Python:列表参数传递

2024-04-18 06:31:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道我们在Python中传递参数时传递对象的引用。你知道吗

所以

def changer(b):
    b[0] = "spam"

l = [1,2]
changer(l)             # l is now ["spam",2]

但是,如果我这么做了

changer(l[:])          # l remains [1,2]

在第二种情况下,当我传递list slice时,传递给函数的是什么?你知道吗


Tags: 对象函数参数isdef情况slicespam
1条回答
网友
1楼 · 发布于 2024-04-18 06:31:57

l[:]创建一个副本。请参见切片。副本被传递到函数中,函数修改l的副本。因此,l将保持不变。你知道吗

All slice operations return a new list containing the requested elements. This means that the following slice returns a new (shallow) copy of the list.

相关问题 更多 >