🔹 Step 1: Tuple creation
t = (10, 20, 30)
A tuple is created.
Tuples are immutable → you cannot change their values.
🔹 Step 2: Loop starts
for i in t:
This means:
-
First iteration → i = 10
-
Second iteration → i = 20
-
Third iteration → i = 30
🔹 Step 3: Condition
if i == 20:i = 99
When i becomes 20, you assign:
i = 99
But ⚠️ this only changes the local variable i,
NOT the tuple.
It’s like:
i = 20i = 99 # only variable changed, not original data
🔹 Step 4: Print
print(t)
The tuple was never modified, so output is:
(10, 20, 30)
Key Concept (Very Important)
Loop variable does not modify immutable objects.
You changed:
-
❌ the variable
-
Not the tuple
❌ This will NEVER work on tuples
t[1] = 99 # Error! Tuples are immutable
✅ Correct way (convert to list)
t = list(t)t[1] = 99t = tuple(t)print(t)
Output:
(10, 99, 30)
Interview One-Liner Answer:
Because tuples are immutable, changing the loop variable does not affect the original tuple.


0 Comments:
Post a Comment