When Does Python’s += Differ From =? The Hidden Pitfall with Mutable Objects
This article explains why Python’s augmented assignment (+=) can produce different results than regular assignment (=) when used with mutable objects like lists, illustrating the shared‑reference behavior and advising caution to avoid unexpected bugs.
Augmented assignment statements such as i += 1 are often preferred for performance, but they are not always equivalent to the corresponding normal assignment i = i + 1, especially when the operand is a mutable object.
Example 1: Using augmented assignment
In [1]: a = [1, 2, 3]
In [2]: b = a
In [3]: b += [1, 2, 3]
In [4]: print a, b
[1, 2, 3, 1, 2, 3] [1, 2, 3, 1, 2, 3]
In [5]: id(a), id(b)
Out[5]: (140213762276096, 140213762276096)Example 2: Using normal assignment
In [6]: a = [1, 2, 3]
In [7]: b = a
In [8]: b = b + [1, 2, 3]
In [9]: print a, b
[1, 2, 3] [1, 2, 3, 1, 2, 3]
In [10]: id(a), id(b)
Out[10]: (140213762466232, 140213762276168)In both examples a list is assigned to a and then a is assigned to b, so initially a and b reference the same list object. With the augmented assignment ( +=), the list is extended in place, keeping the same object ID for both variables. With the normal assignment ( =), a new list is created, so b points to a different object.
The key point is Python’s shared‑reference model: multiple variables can refer to the same mutable object. Augmented assignment modifies the object in place (writing back), while normal assignment creates a new object for the result. Consequently, after += the variables still share one object, but after = they no longer do.
Conclusion: Avoid using augmented assignment on mutable objects unless you fully understand this behavior.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
