Python Tuples Immutability Gotcha

🚨 Most developers get this wrong… will you? t = (1, 2, [3, 4]) t[2].append(5) print(t) At first glance, many assume this throws an error ❌ 💡 Why this matters: - Tuples are immutable - But they can contain mutable objects (like lists) - And those objects can still be modified This small concept highlights a deeper understanding of Python’s data model — something interviewers often look for. 🎯 Key takeaway: «Immutability applies to the container, not necessarily the contents.» 👇 Curious to know: Did you get it right on the first try? #Python #SoftwareEngineering #CodingInterview #Developers #Programming #TechCareers #Learning #PythonTips

  • text

The output is (1,2,[3,4,5]) as it's indexing/accessing the value which is list at 2nd index (positive goes from 0) and as we know list is an mutable datatype, and append() is an attribute of list which only works for list which can add only one value (basically one parameter required) it will simply add the value (5) in that.These kinds of lists are called nested lists as they are inside a tuple. We can access them by indexing and here still considered list as a whole only.

This one is a classic "gotcha" that catches almost everyone! 😅 Most of us are taught that Tuples are "immutable," so we expect a TypeError the moment we see that .append(). But the fun part is how Python actually manages its memory. Think of the Tuple like a strict landlord. He has a list of who lives in each room (the references), and he won’t let you swap a tenant out for a new one. However, he doesn’t care if a tenant decides to buy a new piece of furniture (appending to the list). Since .append() changes the list in-place, the list keeps its same "ID badge" (memory address). The Tuple looks at index 2, sees the same ID badge it started with, and stays perfectly happy. The Result: (1, 2, [3, 4, 5]) It’s a great reminder that in Python, "Immutable" just means the identity of the contents is locked, not necessarily the state of the contents themselves!

After appending: t = (1,2,[3,4,5]) We can use append function inside a list not a tuple, because we can't change tuple, and in this scenario list inside a tuple, so append a 5 at index 2 because this a list at this position.

LOL...Super Easy!!! Output will be (1, 2, [3, 4, 5]) Touple are immutable, but this contain mutable object which is t[2] list in this case, .append(5) modifies that list in-place.

Like
Reply

output will be, (1,2,[3,4,5]), tuple is immutable but there is list inside so we can use append .

(1,2[3,4,5])as the whole list is a single element and it will be added in it as we can mutate lists

Like
Reply

✅ Output: (1, 2, [3, 4, 5]) Here tuple contains a list, and lists can be modified. So t[2].append(5) updates the inner list only.

Like
Reply

Inside the list can take place

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories