Python Tuples and Immutability: A Surprising Twist

Today a friend asked me a simple question: “What will be the output?” T = (1, 2, 3, [4, 5]) try: T[3] += [6] except Exception as e: print(e) print(T) I was confident. Tuple => immutable List => mutable So it should just add 6 to the list… right? Well… Here’s the actual output: ~ 'tuple' object does not support item assignment ~ (1, 2, 3, [4, 5, 6]) Wait… 🤯 If an exception was raised, how did the list change? What’s really happening? T[3] += [6] is not one operation. Python roughly does this: 1. The Fetch: Python gets the list at T[3]. 2. The Mutation: It calls .__iadd__([6]). Because lists are mutable, this modifies the list in-place. The list is now [4, 5, 6]. 3. The Assignment: It tries to assign that list back to T[3]. Step 2 succeeds. ✔️ Step 3 fails. ❌ So the tuple stays immutable But the list inside it was already modified The Real Insight Tuple immutability means: 👉 You cannot change what the tuple references 👉 But you can mutate the object it references (if it’s mutable) Immutability in Python is about bindings and references — not deep contents. And a great reminder that understanding how Python executes operations under the hood makes you a stronger developer. Have you ever been surprised by Python’s behavior like this? #Python #SoftwareEngineering #ProgrammingConcepts #CleanCode #LearningInPublic

To view or add a comment, sign in

Explore content categories