Difference in copying a list in python

This article gives you an explanation on difference between copy and assignment operation in python

Hello all. Today I have learnt about copying a list in python . 

Suppose you want to copy a list into another list, and edit the copied one without affecting original one .

Let's see how we can do this in python and what difference in copying and assignment. 

Open Python Shell by 

   python

 Let's  have a list called a and assign b(another list) = a 

>>> a=[1,2,3,4,5]

>>> b = a

>>> a

[1, 2, 3, 4, 5]


>>> b

[1, 2, 3, 4, 5]

>>> b.pop()
5

>>> b
[1, 2, 3, 4]

>>> a
[1, 2, 3, 4]
>>>

 Let's  As you see in above lines , a list contains 5 elements , then we assign b = a , after printing a and b both are same .

Now Let's pop an element from b and see what happens to a and b . If we pop an element from b it pops an element from a also . 

That's because b=a never creates a list , just reference the same list created for a .   So when a list is created with assignment operator(=) using another list , any changes( append, pop, remove) to list affects both .

So how do we copy one list to another in python 

Python comes with an module called copy  

>>> a = [1,2,3,4,5]

>>> import copy

>>> b = copy.copy(a)

>>> b

[1, 2, 3, 4, 5]

>>> b.pop()

5

>>> b

[1, 2, 3, 4]

>>> a

[1, 2, 3, 4, 5]

>>>

 

As You See copy.copy(a) one creates new list , any operation on copied list b doesn't affect a(original list) .

Thanks for reading . Happy Coding !

 

Leave a comment

(Note: Comments are moderated)