Python Master Course V2 — 037. Tuples and Immutable Records
SMARTYFY ACADEMY · MODULE 04 · Collections and Data Modelling · LESSON 037 / 200
Tuples and Immutable Records
Study time: 70–100 minutes · Prerequisite: Lesson 036 and earlier Python collections lessons.
Video lesson
Video not yet available. Reserved area for a verified video link or embedded player. No video has been uploaded.
Learning outcomes
- Understand the core concepts of tuples and immutable records.
- Predict outputs and explain data changes.
- Choose appropriate data structures and validate inputs.
- Apply the lesson to a practical Python project.
- Identify common mistakes and test edge cases.
Understand the idea, then trace the code
An ordered record whose slots cannot change
A tuple is an ordered sequence like a list: it supports indexing, slicing, iteration, length, and membership. Its defining difference is that its slots cannot be added, removed, or assigned after the tuple is created. Use a tuple for a small positional record whose structure is fixed, such as an x-and-y coordinate. The tuple does not make the variable name permanent; that name can later be rebound to a different tuple.
point = (3, 4)
print(point[0], point[-1])
print(point[:1])
point = (8, 4)
print(point)
Expected output
3 4
(3,)
(8, 4)
The last assignment creates or selects a different tuple and binds point to it. It does not edit the earlier tuple. In contrast, trying point[0] = 8 raises TypeError because item assignment is unsupported. Tuples also have no append or remove method. To describe a revised record, construct a replacement and make the rebinding explicit. This encourages thinking of a record update as a new value.
The comma creates a singleton
Parentheses often group an expression, so (3) is simply the integer three. A one-item tuple needs a trailing comma: (3,). The empty tuple is written (). Multiple comma-separated values can form a tuple without parentheses, although parentheses frequently improve readability. Converting an iterable with tuple(source) consumes its items into a tuple; passing a string produces a tuple of characters, not a one-item tuple containing that string.
print(type((3)).__name__)
print(type((3,)).__name__)
print(tuple("cat"))
print(("cat",))
Expected output
int
tuple
('c', 'a', 't')
('cat',)
Immutability is about the tuple’s own slots
A tuple may refer to mutable objects. Its slots still point to the same objects, but those objects may change internally. A tuple containing a list is therefore not a fully frozen data model. If a record should contain a stable sequence of labels, store a tuple of strings rather than a list of strings. This is a modeling decision; wrapping an existing list in an outer tuple does not convert that list automatically.
labels = ["new"]
record = ("T-7", labels)
labels.append("urgent")
print(record)
Expected output
('T-7', ['new', 'urgent'])
Document positional meaning
A tuple does not name its fields. For a reading record, write down the schema: sensor identifier, whole-number temperature, and unit label, in that exact order. Unpacking gives those positions meaningful local names and checks that the record has the expected number of fields. It does not check their types or business validity. For larger records, repeated numeric indexes become difficult to review; later lessons can introduce named record structures instead of expanding a fragile positional convention.
reading = ("S-2", 21, "C")
sensor, temperature, unit = reading
print(f"{sensor}: {temperature} {unit}")
updated = (sensor, temperature + 1, unit)
print(reading)
print(updated)
Expected output
S-2: 21 C
('S-2', 21, 'C')
('S-2', 22, 'C')
An optional preview: hashability
Hashable objects can be used as dictionary keys or set members, topics developed later. A tuple is hashable only when every element is hashable. A coordinate tuple of integers satisfies that condition; a tuple containing a list does not. Do not simplify this to “all tuples can be keys.” For this lesson, focus on the practical guarantee: tuple slots stay fixed, while the safety of the whole record also depends on the objects stored in those slots.
Progressive runnable example
Setup: Python 3.10 or newer, standard library only. Save as lesson_037.py and run with python lesson_037.py or python3. The outputs below are expected, not claims of execution on the website.
point=(3,4)
x,y=point
print(x+y)
print(point.count(3))
Expected output:
7 1
Walkthrough: Read the starting values, identify each operation’s effect, and explain the resulting collection or return value. Change one input and predict the output before running the code again.
Real-world project — Tuples and Immutable Records application
Summarize validated three-field records with schema (name, quantity, unit_price_minor): names are strings, quantities are positive integers, and prices are nonnegative integer minor units of one currency. For a currency with 100 minor units per major unit, 10 means 0.10. The returned line totals are also minor units. This helper assumes that contract has already been validated; unpacking checks field count, not types or business meaning.
def summarize(records):
return [(name,qty*price) for name,qty,price in records]
print(summarize([("Pen",2,10),("Book",3,40)]))
Expected output:
[('Pen', 20), ('Book', 120)]
Optional later extension: After the file-handling lessons, extend this workflow to import validated CSV records. This is not required for the current lesson.
Testing checklist: Normal input, empty input, single item, duplicates, malformed values and large collections. Document which cases should raise errors and which should return a neutral result.
Common mistakes and professional practices
- Assuming a nonempty collection without checking.
- Accidentally mutating a shared list or nested object.
- Confusing a method’s return value with its in-place effect.
- Ignoring stable ordering or tie-breaking requirements.
- Failing to validate data types and record fields.
- Testing only the happy path rather than boundaries and failures.
Practice: predict, debug, and explain
Try each challenge before opening its answer. Write the result and explain the rule that produces it. The final key question is an optional preview.
1. Identify three different constructions
Predict all three outputs and identify which line creates a one-item tuple.
print((8))
print((8,))
print(tuple([8, 9]))
Optional hint
Look for commas, not just parentheses. The tuple constructor consumes the items of its argument.
Reveal answer and reasoning
Expected output
8
(8,)
(8, 9)
The comma makes the singleton tuple. Parentheses around 8 alone only group an expression. The tuple constructor copies the list’s sequence of references into a tuple.
2. Explain a mutation error
Why does point = (2, 5); point[1] = 9 fail? Show how to create the revised point while preserving the original value.
Reveal answer and reasoning
Assigning a tuple slot raises TypeError. Construct a new tuple instead:
original = (2, 5)
revised = (original[0], 9)
print(original)
print(revised)
Expected output
(2, 5)
(2, 9)
Both values coexist; no slot in original changes.
3. Predict nested mutability
Does the tuple prevent this append? Predict the result.
record = ("A", [10, 20])
record[1].append(30)
print(record)
Reveal answer and reasoning
Expected output
('A', [10, 20, 30])
The append edits the existing list, not the tuple slot referring to it. To make this simple record fully immutable, use a tuple of numbers for the second field.
4. Catch a schema error
The schema is (sensor, temperature, unit). Why does (21, "S-2", "C") still unpack successfully, and what problem remains?
Reveal answer and reasoning
Unpacking checks the number of values, not their meaning. Three fields fit three targets, but the sensor and temperature positions are swapped. Document field order and validate values at the boundary. A valid unpacking operation is not evidence that the data follows the schema.
5. Optional preview: choose a usable coordinate key
Which can serve as a dictionary key: (3, 4), ([3, 4],), or [3, 4]? Explain without relying only on the outer type.
Reveal answer and reasoning
Only (3, 4) is hashable here. Integers are hashable, so the tuple can be hashed. A tuple containing a list is unhashable because that element is unhashable. A list itself is also unhashable. Hashability depends on the tuple’s contents as well as its outer type.
Knowledge check
Use the five topic-specific challenges above as your knowledge check. Explain each answer before revealing its worked reasoning.
Mastery checkpoint
Optional advanced challenge: Add validation, two extra features and five tests to the project. Keep new features within the lesson’s stated input and output contract, and explain the behavior of empty and invalid inputs.
Explain the data structure and operation, run the example, adapt the project and demonstrate at least three edge-case tests. Review the prerequisite lesson if you cannot predict the result.
Summary: Tuples and Immutable Records becomes reliable when paired with clear data models, validation and repeatable testing.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.