Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

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.
left_operand += right_operand
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.

# Mutable example (List)
x = [1, 2]
initial_id = id(x)

x += [3, 4]  # Calls x.__iadd__([3, 4])

print(x)             # Output: [1, 2, 3, 4]
print(id(x) == initial_id)  # Output: True (Memory address is unchanged)

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.

# Immutable example (Integer)
y = 10
initial_id = id(y)

y += 5  # Calls y.__add__(5), then rebinds 'y' to the new object

print(y)             # Output: 15
print(id(y) == initial_id)  # Output: False (Memory address has changed)

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.
t = (1, 2, [3, 4])

try:
    t[2] += [5, 6]
except TypeError as e:
    print(e)  # Output: 'tuple' object does not support item assignment

print(t)      # Output: (1, 2, [3, 4, 5, 6])
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.
Master Python with Deep Grasping Methodology!Learn More