Python List copy()
The copy()
method is used to create a shallow copy of a list.
Syntax
new_list = original_list.copy()
Parameters
The copy()
method doesn’t take any parameters.
Return Value
The copy()
method returns a shallow copy of the list.
Example 1: Copying a list
original_list = [5, 10, 15, 20]
new_list = original_list.copy()
print(new_list) # Output: [5, 10, 15, 20]
If you modify the elements of a new list, the original list won’t be affected.
original_list = [5, 10, 15, 20]
new_list = original_list.copy()
# Modifying the new list
new_list[0] = 90
print(new_list) # Output: [90, 10, 15, 20]
print(original_list) # Output: [5, 10, 15, 20]
However, if the original list contains mutable objects (like other lists or dictionaries), changes made to those inner objects will be reflected in both the original and the copied list.
original_list = [5, 10, [15, 20]]
new_list = original_list.copy()
# Modify an element in the copied list
new_list[0] = 70 # This changes only the copied list
# Modfy an element inside the nested list in the new list
new_list[2][0] = 80 # This changes both lists
print(new_list) # Output: [70, 10, [80, 20]]
print(original_list) # Output: [5, 10, [80, 20]]
If you need to create a completely independent copy of a list, including all nested objects, you need to use deepcopy()
from the copy
module.
import copy
original_list = [5, 10, [15, 20]]
new_list = copy.deepcopy(original_list)
new_list[2][0] = 90
print(new_list) # Output: [5, 10, [90, 20]]
print(original_list) # Output: [5, 10, [15, 20]]