How to clone or copy a list in Python?

PythonServer Side ProgrammingProgramming

In Python, assignment operator doesn’t create a new object, rather it gives another name to already existing object. This can be verified by id() function

>>> L1 = [1,2,3,4]
>>> L2 = L1
>>> id(L1)
185117137928
>>> id(L2)
185117137928

To actually copy a list, following methods can be used.

Slice operator: Two operands of slice operator are index of start and end of slice. If not explicitly used, both default to start end of sequence. We can take advantage of this feature

>>> L1 = [1,2,3,4]
>>> L2 = L1[:]
>>> L1
[1, 2, 3, 4]
>>> L2
[1, 2, 3, 4]
>>> id(L1)
185117025160
>>> id(L2)
185117171592

Another method is to use built-in list() method

>>> L1 =[ 1,2,3,4]
>>> L2 = list(L1)
>>> L1
[1, 2, 3, 4]
>>> L2
[1, 2, 3, 4]
>>> id(L1)
185117295816
>>> id(L2)
185117209352

The copy module of Python’s standard library contains functions for shallow and deep copy of objects. While deep copy is nested copying, in shallow copy, inner list copied by reference only.

>>> import copy
>>> L1 = [1,2,3,4]
>>> L2 = copy.copy(L1)
>>> L1
[1, 2, 3, 4]
>>> L2
[1, 2, 3, 4]
>>> id(L1)
185117025160
>>> id(L2)
185117295880
>>> L3=copy.deepcopy(L1)
>>> L3
[1, 2, 3, 4]
>>> id(L3)
185117304328
raja
Published on 06-Feb-2018 06:42:08
Advertisements