Command Palette

Search for a command to run...

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

Tuples, packing, unpacking and swapping

Add a fourth value to row and run it: what error do you get when unpacking into three names? (type(x).__name__ just gives the name of x's type as text.)

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, packing, unpacking and swapping
Sign in to run this example in your browser.

Expected output

point: (3, 4) | first: 3 | length: 2
single: tuple | not_a_tuple: int
Asha is 21 and lives in Delhi
swapped: 2 1
first: 1 | middle: [2, 3, 4] | last: 5
the list inside changed: (1, [2, 3, 4])