A2oz

How to Deep Copy a List of Lists in Python?

Published in Python Programming 2 mins read

Deep copying a list of lists in Python ensures that you create an entirely independent copy, meaning any modifications to the copy won't affect the original list. This is crucial when you want to work with a list without altering the original data.

Here's how to achieve a deep copy:

Using the copy Module

The copy module provides the deepcopy() function for creating deep copies. This function recursively traverses the list, copying each element and its nested elements.

import copy

original_list = [[1, 2], [3, 4]]
copied_list = copy.deepcopy(original_list)

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

print(f"Original list: {original_list}")
print(f"Copied list: {copied_list}")

Output:

Original list: [[1, 2], [3, 4]]
Copied list: [[10, 2], [3, 4]]

As you can see, changing the copied list doesn't affect the original list.

Using List Comprehension

For simple lists of lists, you can use list comprehension to create a deep copy. This method involves iterating through the original list and creating a new list for each nested list.

original_list = [[1, 2], [3, 4]]
copied_list = [[x for x in sublist] for sublist in original_list]

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

print(f"Original list: {original_list}")
print(f"Copied list: {copied_list}")

Output:

Original list: [[1, 2], [3, 4]]
Copied list: [[10, 2], [3, 4]]

This method also creates an independent copy, allowing you to modify the copied list without affecting the original.

Practical Insights

  • Using the deepcopy() function from the copy module is generally recommended for creating deep copies, especially when dealing with complex nested structures.
  • List comprehension can be a more efficient option for simpler lists of lists.
  • Remember that shallow copying using copy.copy() only creates a copy of the outer list, while the nested lists remain references to the original ones.

Related Articles