Tuples
Tuples: The Safe Container for Data That Shouldn't Change
What You Might Be Wondering
"Lists work fine already. What's the point of tuples?"
When you want data to stay stable — coordinates, config values, return values — a tuple's immutability prevents accidental modification bugs.
One-Line Definition
A tuple is an ordered, immutable sequence.
Real-Life Analogy
A list is like a draft you can keep editing. A tuple is like a signed contract — you don't change it by default.
Minimal Working Example
point = (10, 20)
print(point[0]) # 10
The Single-Element Tuple Gotcha
a = ("python",)
b = ("python")
print(type(a)) # tuple
print(type(b)) # str
One gotcha: without the trailing comma, Python treats the parentheses as just grouping, not a tuple.
Unpacking (Very Common)
name, age = ("Alice", 25)
print(name, age)
Quick Quiz (3 min)
- Define an
(x, y)coordinate and unpack it into separate variables. - Write a function that returns
(min, max). - Check whether an object is a tuple.
Quiz Rubric & Grading Criteria
- Direction: write runnable code that covers the core requirements and edge cases from the prompt.
- Criterion 1 (Correctness): main flow produces correct results, key branches execute.
- Criterion 2 (Readability): clear variable names, no excessive nesting.
- Criterion 3 (Robustness): basic protection against empty values, type errors, or unexpected input.
Take-Home Task
Write a function parse_user() that returns (name, level, is_vip).
Acceptance Criteria
You can independently:
- Create tuples correctly (including single-element ones)
- Use tuple unpacking
- Explain when to pick tuples over lists
Common Errors & Debugging Steps (Beginner Edition)
- Error message looks like gibberish: read the last line for the error type (
TypeError,NameError, etc.), then trace back to the offending line. - Not sure what a variable holds: drop a temporary
print(variable, type(variable))to check. - Changed code but nothing happened: make sure you saved the file, you're running the right file, and your terminal environment (venv) is correct.
Common Misconceptions
-
Misconception:
("x")creates a tuple. -
Reality: single-element tuples need a trailing comma:
("x",). -
Misconception: tuples can't be updated at all.
-
Reality: the tuple itself is immutable, but mutable objects inside it (like lists) can still be modified.