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.
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: (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])