I can not explain the following behaviour:
l1 = [1, 2, 3, 4]
l1[:][0] = 888
print(l1) # [1, 2, 3, 4]
l1[:] = [9, 8, 7, 6]
print(l1) # [9, 8, 7, 6]
It seems to be that l1[:][0]
refers to a copy, whereas l1[:]
refers to the object itself.
Using the copy() methodThe Python List copy() is an inbuilt method copy used to copy all the elements from one list to another. This takes around 1.488 seconds to complete.
To clone a list, one can iterate through the original list and use the clone method to copy all the list elements and use the add method to append them to the list. Approach: Create a cloneable class, which has the clone method overridden. Create a list of the class objects from an array using the asList method.
No, slicing returns a list which is inside the original list. Not a copied list. But, in your code; there is a function which edits the parameter-list. If you are working with parameters, you must know that changes made at a parameter doesn't effect the original variable you pass into it.
This is caused by python's feature that allows you to assign a list to a slice of another list, i.e.
l1 = [1,2,3,4]
l1[:2] = [9, 8]
print(l1)
will set l1
's first two values to 9
and 8
respectively. Similarly,
l1[:] = [9, 8, 7, 6]
assigns new values to all elements of l1
.
More info about assignments in the docs.
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