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

2019-06-15 06:39发布

问题:

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



标签: python slice