Python:列表参数传递

标签 python list

<分区>

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

所以,

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

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

但是,如果我这样做,

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

当我传递列表切片时,第二种情况传递给函数的是什么?

最佳答案

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.

关于Python:列表参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37141739/

相关文章:

Python异常语法差异?

python - django:解析自定义模板中的变量

python - 重新排序图像骨架坐标以使 interp1d 更好地工作

list - 获取对 commonLISP 中函数的 undefined reference

java - 使用方法来比较列表

list - 为什么我的 Prolog 练习没有尝试其他解决方案?

python - 在AWS s3上删除Delta Lake分区的正确方法

从线程 ping 多个 ip 时的 Python ICMP ping 实现?

python - 仅更改列表中第一个元素的方法(列表作为参数传递)

python - 为什么 somelist[len(somelist)] 生成一个 IndexError 而不是 somelist[len(somelist) :]?