Explanation:
๐น Step 1: Create Tuple
x = ([1,2],)
x is a tuple
Tuple contains one list:
[1,2]
๐ Current value:
([1, 2],)
⚠️ Important:
Tuple itself is immutable ❌
But list inside tuple is mutable ✅
๐น Step 2: Execute x[0] += [3]
x[0] += [3]
This line is VERY tricky ๐
Python internally performs TWO operations.
⚡ Step 2.1: Modify the Inner List
[1,2] += [3]
This updates list IN-PLACE.
๐ List becomes:
[1,2,3]
So internally tuple now looks like:
([1,2,3],)
⚡ Step 2.2: Python Tries Reassignment
After modifying list, Python internally tries:
x[0] = [1,2,3]
BUT ❗
Tuple does NOT allow item assignment
Tuple is immutable
So Python raises:
TypeError
๐น Step 3: Error Occurs Before Print
print(x)
This line never executes because error already happened.
⚡ Important Twist ๐
Even though error occurs:
๐ List WAS modified successfully before error
Internally:
x = ([1,2,3],)
BUT print never runs.
๐ฅ Final Result
TypeError

0 Comments:
Post a Comment