Consider a list >>> l=[1,2,3]
.
What is the benefit of using >>> l[:]
when >>> l
prints the same thing as former does?
Thanks.
Consider a list >>> l=[1,2,3]
.
What is the benefit of using >>> l[:]
when >>> l
prints the same thing as former does?
Thanks.
It creates a (shallow) copy.
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 thanl
that contains the same elements. This technique is often used to make shallow copies or clones.http://docs.python.org/tutorial/introduction.html#lists