Make a Deep Copy of a List in Python

To create a deep copy of a list in Python, use the copy.deepcopy() method from the copy module. A deep copy ensures that nested lists (or other mutable objects inside the list) are copied independently, meaning changes in the copied list will not affect the original list.


Examples

1. Creating a Deep Copy Using copy.deepcopy()

The copy.deepcopy() method recursively copies all nested objects, ensuring that modifying the copied list does not affect the original.

</>
Copy
import copy

# Creating a nested list
original_list = [[1, 2, 3], [4, 5, 6]]

# Creating a deep copy using copy.deepcopy()
copied_list = copy.deepcopy(original_list)

# Modifying the copied list
copied_list[0][0] = 99

# Printing both lists
print("Original List:", original_list)
print("Copied List:", copied_list)

In this example:

  1. We import the copy module to use the deepcopy() function.
  2. original_list is a nested list containing two inner lists.
  3. We use copy.deepcopy(original_list) to create copied_list, which is a completely independent copy.
  4. We modify copied_list[0][0] (changing 1 to 99), but original_list remains unchanged.

Output:

Original List: [[1, 2, 3], [4, 5, 6]]
Copied List: [[99, 2, 3], [4, 5, 6]]

2. Difference Between Shallow Copy and Deep Copy

A shallow copy (using copy.copy() or list()) only copies the outer list, meaning changes in the copied list affect the original if there are nested elements.

</>
Copy
import copy

# Creating a nested list
original_list = [[1, 2, 3], [4, 5, 6]]

# Creating a shallow copy
shallow_copy = copy.copy(original_list)

# Modifying the shallow copy
shallow_copy[0][0] = 99

# Printing both lists
print("Original List:", original_list)
print("Shallow Copy:", shallow_copy)
  1. copy.copy(original_list) creates a new outer list but does not copy inner lists independently.
  2. When we change shallow_copy[0][0], the modification also appears in original_list, because both lists share the same nested elements.

Output:

Original List: [[99, 2, 3], [4, 5, 6]]
Shallow Copy: [[99, 2, 3], [4, 5, 6]]

Since a shallow copy shares inner lists with the original, changes in one list reflect in the other. To avoid this, use deepcopy().

Conclusion

To copy a list in Python:

  1. Use copy.deepcopy() for a deep copy (ensuring a completely independent duplicate).
  2. Use copy.copy() or list() for a shallow copy (which shares nested elements with the original).

Deep copies are essential when working with nested lists or objects to prevent unintentional modifications to the original data.