Explanation:
๐น Step 1: Create List Reference
x = y = [1]
⚠️ Important:
Both x and y point to SAME list in memory.
Visual:
x ─┐
├──> [1]
y ─┘
๐ Current value:
x = [1]
y = [1]
๐น Step 2: Execute x += [2]
x += [2]
This is equivalent to:
x.extend([2])
⚠️ += modifies list IN-PLACE.
So original shared list changes.
Visual:
x ─┐
├──> [1,2]
y ─┘
๐ Now:
x = [1,2]
y = [1,2]
๐น Step 3: Execute x = x + [3]
x = x + [3]
⚠️ Very important difference ๐
This does NOT modify existing list.
Instead:
x + [3]
creates a NEW list.
So:
[1,2] + [3]
→ [1,2,3]
Then:
x = [1,2,3]
Now x points to NEW list.
Visual:
y ───> [1,2]
x ───> [1,2,3]
๐น Step 4: Execute print(y)
print(y)
y still points to OLD list:
[1,2]
So output becomes:
[1, 2]
๐ฅ Final Output
[1, 2]

0 Comments:
Post a Comment