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

When reading, list is a reference to the original list, and list[:] shallow-copies the list.

When assigning, list (re)binds the name and list[:] slice-assigns, replacing what was previously in the list.

Also, don't use list as a name since it shadows the built-in.


The latter is a reference to a copy of the list and not a reference to the list. So it's very useful.

>>> li = [1,2,3]
>>> li2 = li
>>> li3 = li[:]
>>> li2[0] = 0
>>> li
[0, 2, 3]
>>> li3
[1, 2, 3]

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[:].

for example:

>>> list1 = [1,2,3]
>>> list2 = list1
>>> list3 = list1[:]
>>> list1[0] = 4
>>> list2
[4, 2, 3]
>>> list3
[1, 2, 3]

Here list2 is changed by changing list1 but list3 doesn't change.

Tags:

Python