The Wayback Machine - https://web.archive.org/web/20250403000443/https://www.geeksforgeeks.org/python-cloning-copying-list/
Open In App

Cloning or Copying a List – Python

Last Updated : 12 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In Python, lists are mutable, meaning they can be modified after creation. Often, we may need to create a copy of a list to preserve the original data while making changes to the duplicate. Cloning or copying a list can be done in multiple ways, each with its own characteristics. Let’s discuss various methods to copy a list in Python.

Using copy()

copy() method is a built-in method in Python that creates a shallow copy of a list. This method is simple and highly efficient for cloning a list.

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

# Copying the list
b = a.copy()

print(b)

Output
[1, 2, 3, 4, 5]

Explanation:

  • The copy() method creates a new list with the same elements as the original.
  • It is a shallow copy, meaning it copies the references of nested objects, not the objects themselves.

Let’s explore some more ways and see how we can clone or copy a list in Python.

Using List Slicing

List slicing is a popular and concise way to create a shallow copy of a list.

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

# Copying the list using slicing
b = a[:]

print(b)  

Output
[1, 2, 3, 4, 5]

Explanation:

  • The slicing operator ([:]) selects all elements from the list.
  • A new list is created with the same elements, separate from the original.

Using list()

list() constructor can be used to create a copy of an existing list.

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

# Copying the list using list()
b = list(a)

print(b)

Output
[1, 2, 3, 4, 5]

Explanation:

  • list() constructor takes an iterable (like a list) as input and creates a new list with the same elements.
  • It creates a shallow copy of the list.

Using List Comprehension

A list comprehension can also be used to copy the elements of a list into a new list.

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

# Copying the list using list comprehension
b = [item for item in a]

print(b) 

Output
[1, 2, 3, 4, 5]

Explanation:

  • The list comprehension iterates through each element of the original list and adds it to the new list.
  • This method is slightly less efficient than slicing or copy() due to the iteration overhead.

Using copy.deepcopy() for Deep Copy

For nested lists, a deep copy is required to ensure that changes to the cloned list do not affect the original. The copy module provides the deepcopy() method for this purpose.

Python
import copy

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

# Copying the list using deepcopy
b = copy.deepcopy(a)

print(b) 

Output
[[1, 2], [3, 4], [5, 6]]

Explanation:

  • deepcopy() function recursively copies all objects inside the list.
  • It ensures that changes to nested objects in the clone do not affect the original.

Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg