Tuples as records and dictionary keys
The last line shows that tuples sort item by item: first items first, and the second items break ties. from collections import namedtuple fetches a ready-made tool (Topic 6.1 teaches import).
A tuple is an ordered collection that cannot be changed after it is created, written with round brackets. Tuples are the natural way to bundle a few related values, and unpacking lets you split a tuple (or any sequence) into separate variables in one line.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Make a tuple birthday = (15, "August", 2010). Unpack it into day, month, year and print 15 August 2010 using those variables.
Given a = 10 and b = 20, swap them without a third variable and print a = 20, b = 10.
Given scores = [60, 70, 80, 90, 100], use star unpacking to get the lowest, the highest and a list of the middle scores. Print all three.
Explain it without notes
What is the difference between a list and a tuple, and when would you choose each?
Why is (5) not a tuple, and how do you write one?
How does a, b = b, a swap two variables?
What does first, *rest = items do?
Is every tuple usable as a dictionary key? What happens with t = (1, [2, 3])?
Expected output
Point(x=3, y=4)
x = 3 | y = 4 | p[1] = 4
unpacked: 3 4
Delhi to Mumbai: 1400 km
at (2, 3): treasure
[(1, 'z'), (2, 'a'), (2, 'b')]