[Python] += with mutable/immutable objects

 += with mutable/immutable objects

while preparing a MCQ section in a coding test, I encountered some patterns with += operator with mutable/immutable objects:

If the object is mutable (like a list), += will modify it in-place.
If the object is immutable (like a string or tuple), += will create a new object.


Why?

Mutable objects (e.g., list, dict, set)

  • Have an in-place method: __iadd__()

  • So x += y calls that method → modifies x without changing its memory address

a = [1, 2]
print(id(a))
a += [3]         # in-place
print(id(a))     # same id ✅

Immutable objects (e.g., str, tuple, int)

  • Cannot be changed once created

  • So x += y is treated as x = x + y → a new object is created and reassigned to x

s = "hi"
print(id(s))
s += " there"    # new string object created
print(id(s))     # different id ❌

📌 What this means in practice:

Type += Behavior In-Place? Example
list Uses .extend() ✅ Yes [1, 2] += [3] → [1, 2, 3]
str Reassigned ❌ No "a" += "b" → "ab" (new string)
tuple New object created ❌ No (1, 2) += (3,) → (1, 2, 3)
int New int created ❌ No x += 1 → new value, old lost


Comments