Python 101: Immutable vs Mutable Objects in Python

In Python, objects are categorized as either mutable or immutable. Understanding the distinction between these two types of objects is crucial for efficient programming and can profoundly influence your decision when choosing which data type to use in solving a given programming problem.

Immutable Objects:

  • Immutable objects do not allow their value or data to be changed in place without affecting the object’s identity.
  • When you modify an immutable object, a new object of the same type with different values is created.
  • Examples of immutable objects in Python include strings, tuples, and numbers.

Mutable Objects:

  • Mutable objects allow you to change their value or data in place without affecting the object’s identity.
  • They are easier to change but are slower to access and more expensive to change because it involves the creation of a copy.
  • Examples of mutable objects in Python include lists, dictionaries, and sets.

Practical Implications

Understanding the concepts of mutability and immutability is crucial, especially when working with Python. By comprehending the concepts of mutability and immutability, developers can write more efficient, reliable, and bug-free code. The choice between mutable and immutable objects can profoundly influence your decision when choosing which data type to use in solving a given programming problem.

In summary, the distinction between mutable and immutable objects in Python is essential for crafting error-free code and can significantly impact your coding approach. It’s important to use immutable objects for values that should not be modified and mutable objects for when you need to modify the object’s state or contents.


1. a = b = c = "value" (Immutable String)

In this case, all three variables a, b, and c are assigned the same value, "value".
在这种情况下,所有三个变量 abc 都被赋予相同的值 "value"

  • Python first evaluates the expression "value".
    Python 首先计算表达式 "value"

  • Then, it assigns "value" to c.
    然后,它将 "value" 赋值给 c

  • Next, c (which now holds "value") is assigned to b.
    接着,c(现在包含 "value")被赋值给 b

  • Finally, b (which holds "value") is assigned to a.
    最后,b(包含 "value")被赋值给 a

Key Point: All three variables point to the same memory location where the string "value" is stored.
关键点:所有三个变量都指向存储字符串 "value" 的同一内存位置。

Since strings are immutable in Python, if you attempt to modify the string through any of these variables, a new string object will be created, and the other variables will remain unchanged.
由于字符串在 Python 中是不可变的,如果您尝试通过其中任何一个变量修改字符串,将创建一个新的字符串对象,而其他变量将保持不变。

Example with String (Immutable):

a = b = c = "value"

# Modifying 'a'
a = a + "d"  # This creates a new string "valued" and assigns it to 'a'

print(a)  # Output: "valued"
print(b)  # Output: "value"
print(c)  # Output: "value"

In this example:
在这个例子中:

  • Initially, a, b, and c all refer to the same string "value".
    最初,abc 都引用同一个字符串 "value"

  • When a is modified by appending "d" to it, Python creates a new string "valued" and assigns it to a.
    当通过在 a 后面添加 "d" 来修改 a 时,Python 会创建一个新的字符串 "valued" 并将其赋值给 a

  • However, b and c continue to refer to the original "value" string because strings are immutable and not changed in place.
    然而,bc 继续引用原始的 "value" 字符串,因为字符串是不可变的,不会原地改变。

Example with List (Mutable):

Now let’s see what happens with a mutable value like a list.
现在让我们看看当值是一个可变对象(如列表)时会发生什么。

a = b = c = []

# Modifying 'a'
a.append(1)  # This modifies the list in place

print(a)  # Output: [1]
print(b)  # Output: [1]
print(c)  # Output: [1]

In this example:
在这个例子中:

  • a, b, and c all refer to the same list.
    abc 都引用同一个列表。

  • When a is modified by appending 1 to the list, the change is reflected in b and c as well, because all three variables point to the same mutable list object.
    当通过在列表中添加 1 来修改 a 时,这一变化也会反映在 bc 中,因为这三个变量都指向同一个可变的列表对象。

2.

a = "value"
b = "value"
c = "value"

In this case, each variable a, b, and c is assigned separately.
在这种情况下,每个变量 abc 都是单独赋值的。

Since the string "value" is immutable and identical, Python optimizes memory usage by having all three variables reference the same string object.
由于字符串 "value" 是不可变且相同的,Python 通过让所有三个变量引用同一个字符串对象来优化内存使用。

  • a is assigned "value".
    a 被赋予 "value"

  • b is assigned "value".
    b 被赋予 "value"

  • c is assigned "value".
    c 被赋予 "value"

Key Point: While this results in a, b, and c referencing the same "value" object, the assignments are done independently.
关键点:虽然这导致 abc 引用同一个 "value" 对象,但赋值是独立完成的。

Since strings are immutable, modifying any one of these variables will result in the creation of a new string object, leaving the other variables unchanged.
由于字符串是不可变的,修改其中任何一个变量将导致创建一个新的字符串对象,而其他变量将保持不变。

Example with List (Mutable):

a = []
b = []
c = []

# Modifying 'a'
a.append(1)  # This modifies the list in place

print(a)  # Output: [1]
print(b)  # Output: []
print(c)  # Output: []

In this example:
在这个例子中:

  • a, b, and c are all assigned separate lists.
    abc 都被赋予了独立的列表。

  • When a is modified by appending 1, only a is affected because b and c refer to different list objects.
    a 被添加 1 时,只有 a 受到影响,因为 bc 引用的是不同的列表对象。

Conclusion 结论

  • Chained assignment (a = b = c = "value"): All variables initially refer to the same string or list object. Since strings are immutable, any operation that seems to modify a string will create a new string object, leaving the other variables unchanged. For mutable objects like lists, modifying the object through one variable will reflect the changes in all variables.
    链式赋值 (a = b = c = "value"):所有变量最初都引用同一个字符串或列表对象。由于字符串是不可变的,任何看似修改字符串的操作都会创建一个新的字符串对象,其他变量将保持不变。对于像列表这样的可变对象,通过一个变量修改对象会反映在所有变量中。

  • Separate assignment (a = "value"; b = "value"; c = "value"): Each variable is independently assigned the same string object, but Python optimizes this by referencing the same immutable object. Modifying one will not affect the others. For mutable objects like lists, each variable gets a distinct object, so changes in one do not affect the others.
    单独赋值 (a = "value"; b = "value"; c = "value"):每个变量都是独立赋值的相同字符串对象,但 Python 通过引用相同的不可变对象来优化这一点。修改其中一个不会影响其他变量。对于像列表这样的可变对象,每个变量得到的是不同的对象,因此一个对象的变化不会影响其他对象。

This distinction is crucial when dealing with mutable objects, but for immutable objects like strings, Python handles memory efficiently by reusing the same object where possible.
这种区别在处理可变对象时尤为重要,但对于像字符串这样的不可变对象,Python 通过在可能的情况下重用相同的对象来有效地处理内存。


Recommend Resources:


by Corey Schafer


by Portfolio Courses


by Python and Pandas with Reuven Lerner


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *