How do we copy a list in python to another list? This might be quite deceiving for novices who have not done our basics right.

Let's have a look at the following sample code:

Copying List: Naive logic

PHP

1

2

3

4

5

import time

start_time=time.time()

li=[3,5,'log',5.7,9.2,3,'change','python',11]

li_copy=li

print"Time taken for execution: ",time.time()-start_time

The output is:

Copying List: Naive logic - Output

PHP

1

Time taken forexecution:1.21593475342e-05

But does it really work? Have all the elements 'really' copied to a new list? I mean, are they having some 'internal bond' with their respective elements in the parent list? Let's try printing the following:

Copying List: Naive logic - Changes

PHP

1

2

li[2]='logging'

printli_copy[2]

Alas, it prints 'logging' though we changed it for the list li. That means, changes made in li also reflects in li_copy as well. This is how naive copying of lists and dict works in Python. We call it 'Shallow Copying". When we simply assign a list to another, or dict to another for that matter, Python just bonds the two with a reference. Changes made in one of them will affect the other one too!

How do we go about this problem? How to do 'really' copy, which we call as 'deep copy' without any internal references? Let's have a look.

One logic is to copy each of the elements over a loop, to another list. When we do so, as given above, there would be no references made between the two lists. Changing something in one list would, obviously, not make changes in the other. The output of the above code is:

Copying List: Deep Copy: Naive Logic - Output

PHP

1

Time taken forexecution:1.90734863281e-05

So we're done with both shallow copy and deep copy, writing our own codes. Is there a package in python which helps do this easily? Yes, we have a module named 'copy', importing which will help you do this in a better way. Have a look at the deep copy: