python - list = [] 与 list.clear() 之间的区别

标签 python python-3.x list

list = []list.clear() 有什么区别?

根据我的代码行为和我自己的观察,list.clear() 删除了它的条目以及我用来附加其数据的条目。

例子:

container.append(list)
list.clear()

container 也将是 []

最佳答案

调用 clear 从列表中删除所有元素。分配 [] 只是将该变量替换为另一个空列表。当您有两个变量指向同一个列表时,这一点就很明显了。

考虑以下片段:

>>> l1 = [1, 2, 3]
>>> l2 = l1
>>> l1.clear()
>>> l1 # l1 is obviously empty
[]
>>> l2 # But so is l2, since it's the same object
[]

与这个相比:

>>> l1 = [1, 2, 3]
>>> l2 = l1
>>> l1 = []
>>> l1 # l1 is obviously empty
[]
>>> l2 # But l2 still points to the previous value, and is not affected
[1, 2, 3]

关于python - list = [] 与 list.clear() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55897375/

相关文章:

python - Python 扩展方法的段错误

python - 如何在 Python 中从 mp4 视频中获取一随机帧?

python-3.x - 无法使用 ctypes 从 python 调用的 c 库中获取 pi

java - Java 中常用的数据结构有哪些?

python - 以最小的内存占用拆分大型 Pandas Dataframe

Python/Twisted - 发送到特定的套接字对象?

python - 如何使用附加信息重新引发异常?

python - 如何在不使用 .pop() 或 .remove() 的情况下从项目列表中删除第一次出现的特定项目

Python:在迭代范围时将范围添加到范围列表中

python - 在 Python 中乘以 Decimal 时的精度损失