Home >Backend Development >Python Tutorial >How Can I Create an Immutable Copy of a List in Python?
Creating an Immutable List Copy
In Python, while assigning list references like new_list = my_list, modifications to new_list surprisingly affect my_list. This occurs because instead of creating a distinct new list, Python merely copies the reference to the actual list, resulting in both new_list and my_list pointing to the same list.
To address this and prevent unexpected changes, it's essential to create a true copy of the list using various methods.
Cloning a List
To obtain an immutable clone or a shallow copy of a list, consider the following options:
new_list = old_list.copy()
new_list = old_list[:]
new_list = list(old_list)
Deep Copying a List
If you need to copy the elements of the list as well, employ deep copying:
import copy new_list = copy.deepcopy(old_list)
Example
Consider the following code:
import copy class Foo: 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) # edit orignal list and instance a.append('baz') foo.val = 5 print(f'original: {a}\nlist.copy(): {b}\nslice: {c}\nlist(): {d}\ncopy: {e}\ndeepcopy: {f}')
Result:
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)]
This demonstrates how modifications to the original list and its instances only affect the original list and not its copied versions (b, c, d, and f).
The above is the detailed content of How Can I Create an Immutable Copy of a List in Python?. For more information, please follow other related articles on the PHP Chinese website!