[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 += ycalls that method → modifiesxwithout changing its memory address
a = [1, 2]print(id(a))a += [3] # in-placeprint(id(a)) # same id ✅
Immutable objects (e.g., str, tuple, int)
-
Cannot be changed once created
-
So
x += yis treated asx = x + y→ a new object is created and reassigned tox
s = "hi"print(id(s))s += " there" # new string object createdprint(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
Post a Comment