How to Copy a List of Lists in Python?

Estimated read time 2 min read

To copy a list of lists in Python, you can use a nested list comprehension or the copy module’s deepcopy() function. Here are examples of both methods:

Using a Nested List Comprehension:

original_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
copied_list = [[element for element in inner_list] for inner_list in original_list]

In this example, we create a list of lists called original_list with three inner lists. We then use a nested list comprehension to create a new list called copied_list that is a copy of the original list.

The outer list comprehension iterates over each inner list in the original list, while the inner list comprehension iterates over each element in the inner list and copies it to a new list.

Using deepcopy() from the copy module:

import copy

original_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
copied_list = copy.deepcopy(original_list)

In this example, we create a list of lists called original_list with three inner lists. We then use the deepcopy() function from the copy module to create a new list called copied_list that is a deep copy of the original list.

A deep copy creates a new object with a new memory address, and recursively copies all objects within the original object, including any nested objects, such as other lists, dictionaries, or tuples. This ensures that any changes made to the copied object do not affect the original object, or any of its nested objects.

Note that for simple lists of lists like the example above, the nested list comprehension is an efficient and straightforward way to copy the list. However, for more complex data structures, the deepcopy() function may be a more robust solution.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply