Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: lists and copy of them

Tags:

python

list

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.

like image 477
fcracker79 Avatar asked Dec 26 '14 15:12

fcracker79


People also ask

Can you make copy of list Python?

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.

How do you clone a list?

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.

Does slicing a list Make a copy Python?

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.


1 Answers

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.

like image 102
Aran-Fey Avatar answered Oct 15 '22 05:10

Aran-Fey