Lists
How to copy a list in Python
Quick answer
Use list.copy() or slicing to create a copy of a list in Python, e.g. my_list.copy() or my_list[:].
my_list = [1, 2, 3]
copied_list = my_list.copy()
print(copied_list)
my_list.append(4)
print(my_list)
print(copied_list)The snippet creates a copy of my_list using the copy method and demonstrates that changes to the original list do not affect the copied list. This approach is efficient and straightforward. However, for nested lists, a deep copy may be necessary to avoid modifying the original list's elements.
Variations
Using Slicing
my_list = [1, 2, 3]
copied_list = my_list[:]
print(copied_list)similar to copy method
Deep Copy
import copy
my_list = [[1], 2, 3]
copied_list = copy.deepcopy(my_list)
print(copied_list)requires pip install copy
List Comprehension
my_list = [1, 2, 3]
copied_list = [x for x in my_list]
print(copied_list)less efficient than copy method
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.