Explanation:
๐น Step 1: Create Tuple
x = ([],)
x is a tuple
Tuple is immutable ❗
Inside tuple:
[]
is a mutable list
๐ Current value:
([],)
๐น Step 2: Execute x[0] += [1]
x[0] += [1]
This line is tricky ๐
Python internally performs TWO actions.
⚡ Step 2.1: Modify the List
[] += [1]
This updates list in-place.
๐ List becomes:
[1]
So internally:
x → ([1],)
⚡ Step 2.2: Try Reassignment
After modifying list, Python also tries:
x[0] = [1]
⚠️ But tuple is immutable ❌
Tuple does NOT allow item assignment.
๐น Step 3: Error Occurs
Python raises:
TypeError
๐ Program stops here
๐น Step 4: print(x) Never Executes
print(x)
This line is never reached because error already happened.
⚡ Important Twist ๐
Even though error occurs:
๐ list WAS modified before error
Internally tuple becomes:
([1],)
But print never runs.
๐ฅ Final Output
TypeError

0 Comments:
Post a Comment