Creating Unmodifiable Clones of Python Lists
When assigning new_list to my_list, it's not an actual separate list creation. Instead, it's just a reference pointing to the same list, causing any changes in new_list to be reflected in my_list.
Copying Lists Effectively
To avoid unexpected list modifications, several methods exist for list cloning:
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)
Example:
class Foo: def __init__(self, val): self.val = val 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') foo.val = 5 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)]
The above is the detailed content of How to Create Truly Independent Copies of Python Lists?. For more information, please follow other related articles on the PHP Chinese website!