Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

slice

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

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

Thanks.

like image 744
Dharmit Avatar asked Feb 09 '11 16:02

Dharmit


People also ask

What is the difference between list [:] and list?

li[:] creates a copy of the original list. But it does not refer to the same list object. Hence you don't risk changing the original list by changing the copy created by li[:]. Here list2 is changed by changing list1 but list3 doesn't change.

What is the meaning of list [: in Python?

List. Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

What does list [:] do in Python?

Definition and Usage. The list() function creates a list object. A list object is a collection which is ordered and changeable. Read more about list in the chapter: Python Lists.

Do lists in Python have to be the same type?

Defining a list in Python is easy — just use the bracket syntax to indicate items in a list. Items in a list do not have to all be the same type, either. They can be any Python object.


1 Answers

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
like image 123
Josh Lee Avatar answered Oct 18 '22 20:10

Josh Lee