SoFunction
Updated on 2025-05-21

Detailed explanation of whether the object of Python variable assignment and reference is mutable

Overview

In Python, the mechanism of variable assignment involves references to objects and variability of objects.Variable names are just references to objects, instead of storing data directly. Therefore, variablesaandbThe difference in behavior after assignment depends on two factors:

  • Is the object variable?(Mutable/Immutable)。
  • Modify the type of operation(Directly modify the object content or reassign the variable).

1. Immutable Objects

Once the value of an immutable object is created, its content cannot be modified, for example:

  • Integer (int
  • String (str
  • Tuple(tuple
  • Boolean value (bool)wait.

Scenario: Modify the new assignment of the change quantity

a = 5         # a points to integer object 5b = a         # b also points to the same integer object 5
a = 6         # At this time a points to the new integer object 6, but b still points to 5
print(b)      # Output 5

reason

  • Assignment operationb = ahour,Copy the reference only, makeaandbAll point to the same object (initially 5).
  • whena = 6hour,aThe reference of  is updated to point to the new object 6, andbStill pointing to the original object 5.
  • Immutable objects cannot be modified, can only recreate new objects, sobWill not change.

Scenario: Try to modify the object content directly (invalid)

a = "hello"   # a point to the string "hello"b = a         #b also points to the same string object
# Try to modify the string content (but the immutable object does not allow this operation)a[0] = "H"    # Error: 'str' object does not support item assignment

result: This operation cannot be performed at all because the string is immutable.

2. Mutable Objects

The value of a mutable object can be modified after creation, for example:

  • List (list
  • dictionary(dict
  • gather(set
  • Custom class instances, etc.

Scenario: directly modify the object content

a = [1, 2]    # a point to list[1, 2]b = a         # b Point to the same list object
(3)   # Modify the list content, the original list becomes [1, 2, 3]
print(b)      # Output [1, 2, 3]

reason

  • aandbPoint to the same list object.
  • append()The method directly modifies the object'sInternal content, so both variables see the same modified object.

Scenario: Modify the reference of the variable (not affecting the other party)

a = [1, 2]
b = a

a = [3, 4]    The reference to # a is updated to the new list [3,4], but b still points to the original list [1,2]
print(b)      # Output [1, 2]

reason

  • a = [3,4]It is a new assignment operation that directly changedareference to point to a new object, andbNot modified, still point to the original list.

3. Core summary

Condition Causes of behavioral differences
ReviseObject content(mutable object) aandbPoint to the same object, modifying the content will affect both parties.
directReassign variables(Any object) aThe reference points to the new object, andbThe quotation of   has not changed, sobThe value of  is not affected.
Try to modifyContents of immutable objects Immutable objects cannot be modified, they can only generate new objects, and the reference to the original object will not be changed. thereforebUnchanged.

4. How to avoid confusion

  • Immutable Objects: If the assigned variable looks like "modifiedab", this is because a new object is actually generated.
  • Variable Objects: If the assigned variable looks like "modifiedab Changes too”,Because two variables point to the same object,Modification will affect both parties。

If you want the two to be independent

  • Use for mutable objectsDeep or shallow copy
    import copy
    b = (a)  # Completely independent copy

Sample table

Sample code Whether to modify the object content aThe value of bThe value of
a = 5; b = a; a = 6 no 6 5
a = [1]; b = a; a[0] = 2 Yes (modify mutable objects) [2] [2]
a = [1]; b = a; a = [2] no [2] [1]
`a = “str”; b = a; a += “1” No (generate new object) "str1" "str"

Key points:

  • Assignment is a copy of referencesb = aOnly let two variables point to the same object.
  • Modify content vs reassignment
    • Modify content: affects all variables pointing to the object.
    • Reassignment: Only modify the reference of the current variable and does not affect other variables.

Summarize

This is the article about whether the object is mutable when the Python variable assignment and reference is mutable. For more related content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!