⚠️ Python Surprise: An error doesn’t undo the change Check out this snippet. At first glance, it looks like a guaranteed "no-op" because we know tuples are immutable: x = (1, 2, [3, 4]) try: x[2] += [5, 6] except TypeError as e: print(f"Error: {e}") print(f"Tuple after error: {x}") Now checkout the output Error: 'tuple' object does not support item assignment Tuple after error: (1, 2, [3, 4, 5, 6]) The error happened, but the list was still updated What's really happening? In Python, x[2] += [5, 6] isn't one atomic action. It’s actually two separate operations: ✅ Step 1 — Mutation Python updates the list in place. [3, 4] → [3, 4, 5, 6] ✔ success ❌ Step 2 — Assignment Python tries to put the updated list back into the tuple. Tuple says: “Nope. I’m immutable.” → TypeError But by then… the mutation already happened. Python doesn't have a "transactional rollback" for this. This can lead to some nasty bugs if you’re not careful with mutable objects inside "immutable" containers. Have you ever run into a Python behavior that felt like it was breaking its own rules? Let’s hear it in the comments! #python #PythonProgramming #coding #LearnPython
This is a classic 'Augmented Assignment' trap! I faced a similar logic challenge while handling data structures for my DSA Dashboard project. Even though we think of tuples as safe, the fact that they hold references to mutable objects like lists can lead to such bugs. This is exactly why deep copying or using immutables only is so important in production. Have you tried using NamedTuples to avoid this?
Now that's a great thing to recall our Python basics, It always amazes us and serves as an alert for what we are using. We are so focused on big tasks that we turn a blind eye to these blocks, I feel this is a reason too for us to get a few such bugs in our production codes. Good One.
You're modifying the *list* then trying to assign the list to the tuple item. The tuple update fails, but the list is already modified, and the tuple item still refers to the same list
Tuples are immutable.
Fond memories of the type declaration required in C for a const-ptr-to-const-value. Any takers?
Wow. I need a 😯 smiley as a reaction!
Cool first year of college test question !
Just cause a container is immutable, doesn't mean the containers inside it are, python works via references, so the pointer to the list doesn't change, it's not a bug, it's intended behavior