In Python, to create a deep copy of a list (or any mutable object), you can use the copy
module or other techniques. A deep copy means that all objects contained in the original list are recursively copied, rather than just copying the references to those objects.
Method 1: Using copy
Module
Python provides a deepcopy()
function in the copy
module for creating a deep copy of a list.
import copy
original_list = [1, [2, 3], [4, 5]]
deep_copy_list = copy.deepcopy(original_list)
# Modify the deep copy
deep_copy_list[1][0] = 99
print("Original List:", original_list) # Output: [1, [2, 3], [4, 5]]
print("Deep Copy List:", deep_copy_list) # Output: [1, [99, 3], [4, 5]]
Explanation:
copy.deepcopy()
creates a new list and recursively copies all the objects, meaning changes todeep_copy_list
will not affectoriginal_list
.- In the example, modifying the deep copy does not affect the original list.
Method 2: Using List Comprehension for Simple Lists
If the list does not contain nested objects (e.g., no sublists), you can simply copy the list using a list comprehension.
original_list = [1, 2, 3, 4]
deep_copy_list = [item for item in original_list]
# Modify the deep copy
deep_copy_list[0] = 99
print("Original List:", original_list) # Output: [1, 2, 3, 4]
print("Deep Copy List:", deep_copy_list) # Output: [99, 2, 3, 4]
Method 3: Using list()
Constructor
Another way to create a shallow copy (not deep, but good for non-nested lists) is using the list()
constructor:
original_list = [1, 2, 3, 4]
deep_copy_list = list(original_list)
# Modify the deep copy
deep_copy_list[0] = 99
print("Original List:", original_list) # Output: [1, 2, 3, 4]
print("Deep Copy List:", deep_copy_list) # Output: [99, 2, 3, 4]
Method 4: Using Slicing for Non-Nested Lists
For simple, non-nested lists, you can also use slicing to create a shallow copy:
original_list = [1, 2, 3, 4]
deep_copy_list = original_list[:]
# Modify the deep copy
deep_copy_list[0] = 99
print("Original List:", original_list) # Output: [1, 2, 3, 4]
print("Deep Copy List:", deep_copy_list) # Output: [99, 2, 3, 4]
Conclusion:
- Use
copy.deepcopy()
when working with nested objects or lists, as it ensures all levels of the list are copied. - For non-nested lists, you can use list comprehension,
list()
, or slicing to copy the list, but these are shallow copies, meaning they will not fully copy nested objects.