While using new_list = my_list
, any modifications to new_list
changes my_list
every time. Why is this, and how can I clone or copy the list to prevent it?
Python List – How to Clone a List to Prevent Unexpected Changes After Assignment
clonelistmutablepython
Best Answer
new_list = my_list
doesn't actually create a second list. The assignment just copies the reference to the list, not the actual list, so bothnew_list
andmy_list
refer to the same list after the assignment.To actually copy the list, you have several options:
You can use the built-in
list.copy()
method (available since Python 3.3):You can slice it:
Alex Martelli's opinion (at least back in 2007) about this is, that it is a weird syntax and it does not make sense to use it ever. ;) (In his opinion, the next one is more readable).
You can use the built-in
list()
constructor:You can use generic
copy.copy()
:This is a little slower than
list()
because it has to find out the datatype ofold_list
first.If you need to copy the elements of the list as well, use generic
copy.deepcopy()
:Obviously the slowest and most memory-needing method, but sometimes unavoidable. This operates recursively; it will handle any number of levels of nested lists (or other containers).
Example:
Result: