Home  >  Article  >  Backend Development  >  How to Create Truly Immutable Nested Lists in Python?

How to Create Truly Immutable Nested Lists in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-11-20 01:19:03969browse

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:

  • Shallow Copy:

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
  • Deep Copy using Slicing:

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
  • Deep Copy with Copy.deepcopy():

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn