Given a list of elements, the task is to create a copy of it. Copying a list ensures that the original list remains unchanged while we perform operations on the duplicate. This is useful when working with mutable lists, especially nested ones.
For example:
a = [1, 2, 3, 4, 5]
b = a.copy()
Output: [1, 2, 3, 4, 5]
Let’s explore different methods to clone or 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.
a = [1, 2, 3, 4, 5]
b = a.copy()
print(b)
Output
[1, 2, 3, 4, 5]
Explanation: copy() creates a new list with the same elements. Changes to b do not affect a. For nested lists, it still copies references only (shallow copy).
Using List Slicing
This method creates a new list by slicing all elements from the original. It’s concise and performs well.
a = [1, 2, 3, 4, 5]
b = a[:]
print(b)
Output
[1, 2, 3, 4, 5]
Explanation: The [:] operator selects all elements and creates a new list, independent of the original.
Using list()
This method uses Python’s list() constructor to generate a copy of the original list.
a = [1, 2, 3, 4, 5]
b = list(a)
print(b)
Output
[1, 2, 3, 4, 5]
Explanation: list(a) converts the iterable a into a new list. This is also a shallow copy.
Using List Comprehension
A list comprehension can also be used to copy the elements of a list into a new list.
a = [1, 2, 3, 4, 5]
b = [item for item in a]
print(b)
Output
[1, 2, 3, 4, 5]
Explanation: Iterates through a and appends each element to a new list b. Useful if additional processing is needed during copy.
Using copy.deepcopy() for Nested Lists
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.
import copy
a = [[1, 2], [3, 4], [5, 6]]
b = copy.deepcopy(a)
print(b)
Output
[[1, 2], [3, 4], [5, 6]]
Explanation: deepcopy() recursively copies all elements and nested objects. Changes in b do not affect a at any level.