Skip to main content
The += operator is an augmented assignment operator that performs in-place addition. It evaluates the sum or concatenation of the left and right operands and binds the resulting value to the identifier on the left side.
While conceptually similar to left_operand = left_operand + right_operand, the exact behavior of += depends entirely on the mutability of the left operand and its implementation of Python’s data model (magic methods).

Under the Hood: __iadd__ vs __add__

When the Python interpreter encounters x += y, it attempts to execute the operation in a specific order based on the underlying CPython object methods.

1. Mutable Types (__iadd__)

If the left operand is a mutable object (like a list or bytearray), Python looks for the __iadd__ (in-place add) dunder method. If __iadd__ is implemented, the object modifies itself directly in memory. The variable identifier remains bound to the exact same memory address.

2. Immutable Types (__add__)

If the left operand is an immutable object (like an int, float, str, or tuple), it cannot be modified in place. It lacks the __iadd__ method. Python falls back to the standard addition method, __add__. It evaluates x + y, creates a completely new object in memory to hold the result, and then rebinds the left identifier to this new memory address.

The Two-Step Evaluation Caveat

Because += is fundamentally an operation followed by an assignment, it can produce anomalous behavior when mixing mutable and immutable types. If a mutable object is nested inside an immutable container, applying += to the mutable object will result in both a successful mutation and a TypeError.
Execution sequence for the above anomaly:
  1. Python evaluates t[2], retrieving the list [3, 4].
  2. It calls __iadd__([5, 6]) on the list. The list successfully mutates in place to [3, 4, 5, 6].
  3. Python attempts the assignment step: t[2] = <mutated_list>.
  4. The assignment fails because t is a tuple (immutable), raising the TypeError, even though the underlying list was already successfully modified in step 2.
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More