Dharmit
Dharmit

Reputation: 5908

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

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

Answers (2)

recursive
recursive

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

Josh Lee
Josh Lee

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

Related Questions