Python Tuples — Python Technical Interview Questions & Answers
Python Tuples
Python Tuples
- A tuple is an ordered collection that cannot change after you create it. t = (3, 4) is a point. t[0] = 9 raises TypeError. No append, no remove. Use it for fixed records and as dict keys when the items are hashable. Syntax is parentheses, or even 1, 2, 3 without them.
- One-item trap: (42,) is a tuple. (42) is just the int 42 in brackets. Freshers miss the comma and then wonder why t[0] fails. Interview line: ordered + immutable.
- Python Tuples — output: 7. Uncomment assignment and it crashes — tuple cannot change.
point = (3, 4) immutable
x=3 y=4Technical Interview Tip: (42,) vs (42) trap.
Code Examples for Python Tuples
Example
# Tuples
point = (3, 4)
x, y = point
print(x + y)
# point[0] = 9 # TypeError
Python Tuples — output: 7. Uncomment assignment and it crashes — tuple cannot change.
How to Explain Python Tuples to an Interviewer
Explain Tuples as if you are teaching a junior — definition, then one tiny script.
Ordered + immutable. (42,) needs the comma.
What does the example print, and why?
Python Tuples — output: 7
What mistake do freshers make with Tuples?
Fixed records / dict keys.