Cloning Lists for Unaltered Assignment: A Comprehensive Guide
In Python, assigning a list to a new variable using new_list = my_list isn't a genuine copy. Instead, a reference to the original list is created. Consequently, modifications to the new list also alter the original list.
To prevent these unexpected changes, it's essential to clone or copy the list. Here are several approaches:
new_list = old_list.copy()
new_list = old_list[:]
new_list = list(old_list)
import copy new_list = copy.copy(old_list)
import copy new_list = copy.deepcopy(old_list)
Consider a sample with a nested list and an instance:
class Foo(object): def __init__(self, val): self.val = val def __repr__(self): return f'Foo({self.val!r})' foo = Foo(1) a = ['foo', foo] b = a.copy() c = a[:] d = list(a) e = copy.copy(a) f = copy.deepcopy(a) a.append('baz') # Modify original list foo.val = 5 # Modify nested instance print(f'original: {a}\nlist.copy(): {b}\nslice: {c}\nlist(): {d}\ncopy: {e}\ndeepcopy: {f}')
Output:
original: ['foo', Foo(5), 'baz'] list.copy(): ['foo', Foo(5)] slice: ['foo', Foo(5)] list(): ['foo', Foo(5)] copy: ['foo', Foo(5)] deepcopy: ['foo', Foo(1)]
As you can see, while the original list and nested instance changed, only the deepcopy (f) has copied them accurately, preserving previous values.
The above is the detailed content of How Can I Create a True Copy of a Python List to Avoid Unintentional Modifications?. For more information, please follow other related articles on the PHP Chinese website!