Home > Article > Backend Development > How to Create Truly Immutable Nested Lists in Python?
Creating Immutable Nested Lists in Python
Copying data structures in Python can be tricky, especially when dealing with nested lists. Shallow copies using [:] preserve references to nested elements, causing unwanted modifications.
To address this issue, when creating copies of nested lists, consider the following techniques:
For one-dimensional lists, the [:] operator creates a shallow copy that references the same elements in memory. Modifying the copy does not affect the original.
a = [1, 2] b = a[:] b[0] = 3 # Modifies b, but a remains unchanged
For nested lists, slicing alone is insufficient for deep copies. While it creates a new list, the nested elements are still references to the originals.
a = [[1, 2], [3, 4]] b = a[:] # Shallow copy b[0][0] = 5 # Modifies b and a
The copy.deepcopy() function creates true deep copies, recursively creating new objects for all levels of the nested list. Changes made to the copy do not affect the original.
import copy b = copy.deepcopy(a) b[0][0] = 6 # Modifies b, but a remains untouched
By employing these techniques, you can create immutable nested lists that provide isolation, preventing unexpected modifications to the original data structure.
The above is the detailed content of How to Create Truly Immutable Nested Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!