Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.3 — Tuples and Unpacking
Python · Example 2 of 2

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.

01

Make a tuple birthday = (15, "August", 2010). Unpack it into day, month, year and print 15 August 2010 using those variables.

02

Given a = 10 and b = 20, swap them without a third variable and print a = 20, b = 10.

03

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

01

What is the difference between a list and a tuple, and when would you choose each?

02

Why is (5) not a tuple, and how do you write one?

03

How does a, b = b, a swap two variables?

04

What does first, *rest = items do?

05

Is every tuple usable as a dictionary key? What happens with t = (1, [2, 3])?

Tuples as records and dictionary keys
Sign in to run this example in your browser.

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')]