Reputation: 5908
Consider a list >>> l=[1,2,3]
.
What is the benefit of using >>> l[:]
when >>> l
prints the same thing as former does?
Thanks.
Upvotes: 14
Views: 729
Reputation: 86064
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
Upvotes: 12
Reputation: 177550
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
Upvotes: 36