Code Explanation:
๐น Step 1: Create Tuple
a = (1, [2, 3])
A tuple is created → (1, [2, 3])
Tuple is immutable ❌
But it contains a list [2, 3], which is mutable ✅
๐น Step 2: Perform += Operation
a[1] += [4]
This line is the main trick ๐
๐ Python internally does:
Modify the list
Then try to assign it back
๐น Step 2.1: List Gets Modified ✅
[2, 3] → [2, 3, 4]
This works because list is mutable
๐น Step 2.2: Tuple Assignment Fails ❌
a[1] = [2, 3, 4]
Python tries to reassign value inside tuple
❌ Not allowed → tuple is immutable
๐ So error occurs:
TypeError: 'tuple' object does not support item assignment
Final Output:
Error

0 Comments:
Post a Comment