SoFunction
Updated on 2025-04-14

Principles of immutable data types and practical analysis in Python

Introduction: Why Python distinguishes between mutable and immutable

In the Python world, data objects are clearly divided into two camps: Mutable and Immutable. This design is not arbitrary, but a strategic choice made by the Python language in terms of memory management, thread safety, hash computing, etc. Immutable data types are like "read-only files" in life - you can read and copy, but you can't modify their content. The advantages brought by this feature will be analyzed in detail later.

1. The core characteristics of immutable data types

1. Value immutability

Memory mechanism: When trying to modify an immutable object, Python does not change the original object, but creates a new object. For example:

a = 10
b = a
a += 5
print(id(a), id(b))  # Output different memory addresses

Essential reason: Immutable objects are assigned to fixed memory blocks when they are created, and any modification operation will trigger the allocation of new memory blocks.

2. Hash stability

Dictionary key requirements: Only immutable objects can be used as keys for dictionaries because their hash values ​​remain unchanged throughout their lifetime.

Collection element requirements: Immutable objects can also be used as collection elements to ensure the accuracy of the judgment of the uniqueness of the element.

3. Thread safety

Advantages of multi-threading: Immutable objects naturally support multi-threading safety and can be used in concurrent scenarios without locking.

Case comparison: Using tuples (immutable) as data passing between threads is safer and more reliable than lists (mutable).

2. In-depth analysis of five immutable data types

1. Number type (int/float/complex)

Memory optimization: small integers (-5~256) are globally unique, large integers and floating-point numbers are created on demand.

Operation characteristics: Each operation generates a new object, but the interpreter will reuse objects of the same value.

Special case: Although the plural type contains two parts, the whole is still considered immutable.

2. String (str)

Modification restrictions: All "modification" operations (such as splicing, replacement) will generate new strings.

Memory efficiency: The string residency mechanism optimizes duplicate string storage.

Performance Trap: Frequent string stitching should use join() or.

3. Tuple (tuple)

Orderly immutable: Supports index access, but prohibits addition, deletion and modification of elements.

Special case: Tuples containing mutable elements (such as nested lists) do not have deep immutability.

Performance Advantages: Tuple creation and access speeds are better than lists, suitable for storing fixed datasets.

4. Freeze set (frozenset)

Collection characteristics: elements are unique, disordered, and cannot be modified.

Usage scenario: When collection features are required but modification is prohibited (such as configuring constant collections).

Conversion method: Created by the frozenset() constructor, or converted from a normal set.

5. Boolean value (bool)

Essential implementation: True and False are singleton objects with unique memory addresses.

Operational characteristics: Boolean operations return a new object, but the interpreter always multiplexes the two instances.

3. Three core advantages of immutable data types

1. Memory efficiency optimization

Object multiplexing: Only one immutable object with the same value is stored in memory.

Garbage recycling: Immutable objects are more easily identified as garbage, improving recycling efficiency.

Case comparison: When processing 1 million identical strings, the memory usage is only 1/10 of the mutable object.

2. Hash performance improvement

Quick search: pre-calculation of immutable object hash value, dictionary search time complexity O(1).

Security: Hash stability prevents logical errors caused by dictionary key conflicts.

3. Thread safety assurance

Lockless programming: Multi-threaded shared immutable objects without locking, improving concurrency performance.

Case verification: Using tuples as inter-thread message carriers, throughput increased by 3 times.

4. Typical application scenarios of immutable data types

1. Dictionary keys and collection elements

Configuration management: Use immutable objects as keys to the configuration dictionary to ensure configuration stability.

Data deduplication: Use collections to store immutable elements to achieve efficient deduplication.

2. Function parameter passing

Tamper-proof design: Use immutable objects as function parameters to avoid accidental modifications.

Case practice: Financial computing functions receive tuple parameters to ensure the integrity of input data.

3. Multi-threaded data sharing

Task Queue: Use immutable objects to build a thread-safe task queue.

State delivery: Pass state information between coroutines through immutable objects.

4. Cache key design

Cache optimization: Use immutable objects as cache keys to improve cache hit rate.

Case verification: Use tuples as Redis cache keys to increase query speed by 50%.

5. Data serialization

Transmission security: Immutable objects are deterministic after serialization to avoid transmission errors.

Case practice: Use frozen collections to store API response data to ensure the consistency of client parsing.

5. Immutable vs. Variable: How to choose

characteristic Immutable Type Variable Type
Memory usage Low (Object multiplexing) High (independent copy)
Modification cost High (need to create a new object) Low (modified in place)
Thread safety yes No (lock required)
Hash support yes no
Applicable scenarios Dictionary keys, thread sharing data Frequently modified data collection

Select a policy:

When hash support or thread safety is required → immutable type

When frequent modifications are required or memory sensitive → variable types

Intermediate route: Use immutable structures such as namedtuple to improve code readability

6. Practical skills: Efficient use of immutable features

Tuple Unpacking:

data = (42, "Python", 3.14)
code, name, version = data  # Quick unpacking

String formatting:

template = "Value: {value}, Type: {type}"
print((value=42, type="int"))

Freeze set operation:

set1 = frozenset({1,2,3})
set2 = frozenset({3,4,5})
print(set1 | set2)  # union operation

Dictionary key optimization:

# Inefficient waykey = ["user", 123]
# Efficient waykey = ("user", 123)

Function parameter protection:

def process_data(config_tuple):
    # Make sure the configuration parameters are not modified    return config_tuple[0] * config_tuple[1]

Conclusion: The Design Philosophy of Immutability

Python implements it through immutable data types:

The art of balance between memory and performance

Natural barrier to thread safety

The stable cornerstone of hash computing

Understanding immutable features is like mastering Python's "force" - it can not only avoid bugs caused by accidental modifications, but also build efficient and stable data structures. Next time you face type selection, you might as well think more: Does this data need to be changed? If not, use the immutable type!

This is the article about the principle of immutable data types and practical analysis in Python. For more related content on Python immutable data types, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!