Consider a list >>> l=[1,2,3]
.
What is the benefit of using >>> l[:]
when >>> l
prints the same thing as former does?
Thanks.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With