Explanation:
๐น Line 1: Create a Tuple
x = (1, 2)
A tuple containing two elements is created.
Current value:
x = (1, 2)
Memory:
x
│
▼
(1, 2)
๐น Line 2: Add Another Tuple
x += (3,)
This looks like it is modifying the tuple.
Many people think:
(1,2)
becomes
(1,2,3)
inside the same object.
❌ That's not what happens.
๐น What Does += Mean for Tuples?
For tuples,
+=
is equivalent to:
x = x + (3,)
Python performs tuple concatenation, not tuple modification.
๐น Step 1: Evaluate Right Side
Python first evaluates:
x + (3,)
Current tuple:
(1, 2)
Second tuple:
(3,)
Concatenation result:
(1, 2, 3)
A new tuple is created.
๐น Step 2: Assign Back to x
Now Python executes:
x = (1, 2, 3)
Notice:
The old tuple:
(1, 2)
is not modified.
Instead:
Old tuple remains unchanged.
A new tuple is created.
x now points to the new tuple.
๐น Memory Before +=
x
│
▼
(1, 2)
๐น Memory After +=
Old Tuple
(1, 2)
✖ x no longer points here
New Tuple
(1, 2, 3)
▲
│
x
๐น Line 3: Print the Tuple
print(x)
Current value of x:
(1, 2, 3)
Output:
(1, 2, 3)

0 Comments:
Post a Comment