Learn and Learn

Learn And Learn - great place for tutorials, references and how-to

How to Clone or Copy a List in Python

We can use different methods to copy or clone any list in Python. The speed and performance are the only parameters on which you can choose a method to copy a list in Python. Let’s discuss these possibilities one by one.

Using a slicing Method to Clone or Copy a List in Python


Output:
Old list: [1, 2, 3, 4]
New copied list: [1, 2, 3, 4]

 

Using list() Method to Clone or Copy a List in Python

List() is a built-in function in Python programming language to copy or clone lists. Look at the following example for more clarity.
Example:

Output:
Old list: [1, 2, 3, 4]
New copied list: [1, 2, 3, 4]

 

Using copy.copy() Method to Clone or Copy a List in Python

We cannot use copy.copy() method straight forward. We have to import the copy module first. Following example explain this point quite clearly.
Example

Output:
Old list: [1, 2, 3, 4, ['a', 'b', 'c']]
New coppied list: [1, 2, 3, 4, ['a', 'b', 'c']]

 

Using copy.deepcopy() Method to Clone or Copy a List in Python

copy.deepcopy() method is used when the list contains other objects and we want to copy or clone them all.
For more detail look at the following example:

Output:
Old list: [1, 2, 3, 4, ['a', 'b', 'c']]
New copied list: [1, 2, 3, 4, ['a', 'b', 'c']]

 

LearnAndLearn.com © 2018 - All rights reserved