Mutable vs Immutable Types in Python: Why a += b Differs from a = a + b
This article explains Python's mutable and immutable types, shows why a += b and a = a + b behave differently for lists and dictionaries, and clarifies the underlying __add__ versus __iadd__ methods with illustrative diagrams.
Mutable and Immutable Types
To understand whether a += b and a = a + b produce the same result, you must first know what mutable and immutable variables are.
Immutable Types in Python
Immutable: numbers, strings, tuples
Mutable: lists, dictionaries
Immutable Type Operation Examples
1. Immutable +=
2. Immutable =+
For immutable types, the results of += and =+ are identical.
Mutable Type Operation Examples
1. Mutable +=
2. Mutable =+
Comparing the images shows that for mutable types the variables behave differently: after a += b both references change, but after a = a + b only the left‑hand variable points to a new object while the other reference stays unchanged.
Key Takeaway
Remember the conclusion above: the difference lies in the underlying methods __add__ and __iadd__.
Difference Between __add__ and __iadd__
__add__receives two arguments and returns their sum; both arguments remain unchanged. __iadd__ receives two arguments, but the first argument is modified in place.
When a mutable type uses the plus operator as a = a + b, __add__ creates a new object, leaving the original unchanged. When using a += b, __iadd__ modifies the existing object, so all references to it see the change.
Illustrative diagrams:
After a = a + b, a1 points to a new result while a2 remains unchanged.
After a += b, a1 's contents change in place, so a2 also reflects the change.
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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
