SoFunction
Updated on 2024-10-30

Python mutable and immutable object principle analysis

I. Principles

  • Variable objects: list dict set
  • Immutable objects: tuple string int float bool

1. python does not allow programmers to choose between passing values and passing references. python parameter passing is definitely "passing object references". In fact, this method is a combination of passing values and passing references. If the function receives a reference to a mutable object, it can modify the original value of the object - the equivalent of passing an object by reference. If the function receives a reference to an immutable object, it cannot directly modify the original object - the equivalent of passing an object by "value".

2. When one copies a mutable object, one copies a reference to the mutable object, and if one changes the value of the reference, one modifies the original parameter.

3. In order to simplify memory management, Python implements automatic garbage collection through the reference counting mechanism. Each object in Python has a reference count, which is used to count how many times the object has been referenced in different places. Whenever a Python object is referenced once, the corresponding reference count increases by 1. Whenever a Python object is destroyed once, the corresponding reference decreases by 1. Only when the reference count reaches zero is the Python object actually deleted from memory.

II. Specific applications

1. = vs. copy vs. deepcopy

The = assignment does not create a new object; b and a reference the same object.

The copy method creates a new object, b and a refer to different objects, but the mutable object inside (list y) still refers to the same object. In other words, the copy method only copies the outermost layer, and the inner layer doesn't create a new object, but uses the original object, which is a shallow copy.

The deepcopy method creates new objects, and the mutable objects inside it create new objects. Actually deepcopy is a recursive copy, a deep copy.

code example

# = assignment
a = {'x': 11, 'y': [22, 33]}
b = a
print(id(a))
>>> 1630605400840
print(id(b))
>>> 1630605400840

# copy method
a = {'x': 11, 'y': [22, 33]}
b = ()
print(id(a))
>>> 2357161715536
print(id(b))
>>> 2357161715608
print(id(a['y']))
>>> 140720772330640
print(id(b['y']))
>>> 140720772330640

# deepcopy method
import copy
a = {'x': 11, 'y': [22, 33]}
b = (a)
print(id(a))
>>> 2357161715536
print(id(b))
>>> 2357161715608
print(id(a['x']))
>>> 140720772330640
print(id(b['x']))
>>> 140720772330640
print(id(a['y']))
>>> 2462852627784
print(id(b['y']))
>>> 2462852628232

This is the whole content of this article.