Python : Why use “list[:]” when “list” refers to s

2019-06-15 06:14发布

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

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

Thanks.

标签: python slice
2条回答
Anthone
2楼-- · 2019-06-15 06:47

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
查看更多
男人必须洒脱
3楼-- · 2019-06-15 07:00

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

查看更多
登录 后发表回答