Python : Why use “list[:]” when “list” refers to same thing?

我的梦境 提交于 2019-12-23 07:04:57

问题


Consider a list >>> l=[1,2,3].

What is the benefit of using >>> l[:] when >>> l prints the same thing as former does?

Thanks.


回答1:


It creates a (shallow) copy.

>>> l = [1,2,3]
>>> m = l[:]
>>> n = l
>>> l.append(4)
>>> m
[1, 2, 3]
>>> n
[1, 2, 3, 4]
>>> n is l
True
>>> m is l
False



回答2:


l[:] is called slice notation. It can be used to extract only some of the elements in the list, but in this case the bounds are omitted so the entire list is returned, but because of the slice, this will actually be a reference to a different list than l that contains the same elements. This technique is often used to make shallow copies or clones.

http://docs.python.org/tutorial/introduction.html#lists



来源:https://stackoverflow.com/questions/4947762/python-why-use-list-when-list-refers-to-same-thing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!