Module lessons (2/4)
Tuples and unpacking
A tuple is an ordered and immutable sequence: once created, you can no longer change its elements. It is written with parentheses (even though what actually defines it is the comma).
Creating a tuple
vuota = ()
una = (42,) # ATTENZIONE: senza virgola, (42) è solo 42 fra parentesi
coords = (10, 20)
mista = ("Ada", 36, True)Access by index and slicing work exactly like for lists: coords[0],
coords[-1], mista[:2].
When to use a tuple instead of a list
- When the value represents a fixed collection that must not change
(coordinates, a date as
(year, month, day), a version(1, 2, 3)). - When you need to use the value as a dictionary key or as an element of
a
set: only immutable (hashable) objects can be used. - When you want to signal to the reader of the code that that value is "frozen".
Unpacking: the feature that changes how you write Python
nome, anni = ("Ada", 36)
nome # 'Ada'
anni # 36It also works without parentheses (it's the comma that defines the tuple):
x, y = 10, 20And it allows swapping without a temporary variable, a pure Python idiom:
a, b = 1, 2
a, b = b, a
a, b # (2, 1)Unpacking with * (rest)
When you want to capture "the first and the rest" or "the first, the last, the middle":
primo, *resto = [1, 2, 3, 4, 5]
primo # 1
resto # [2, 3, 4, 5]
primo, *centro, ultimo = [1, 2, 3, 4, 5]
centro # [2, 3, 4]This is called starred assignment: the star collects everything that remains into a list.
The single-element tuple trap
(42) is not a tuple, it's the number 42 inside parentheses. To make a
single-element tuple you need the comma: (42,). Without it, any operation
fails in a confusing way.
x = (42)
type(x) # <class 'int'>
x = (42,)
type(x) # <class 'tuple'>Single-element tuples
To create a tuple containing only one element, parentheses alone are not enough: you must insert a trailing comma, for example t = (42,). Without the comma, Python treats the parentheses as simple mathematical grouping, creating a plain integer 42.
Try it
Given `a = 1` and `b = 2`, swap their values in a single line (tuple unpacking) and evaluate the tuple (a, b).
Show hint
a, b = b, a
Solution available after 3 attempts
Review exercise
From the list `voti = [7, 5, 8, 6, 9]`, use unpacking to extract the first grade into `primo`, the last into `ultimo` and the remaining ones into `centro`. Evaluate `(primo, centro, ultimo)`.
Show hint
primo, *centro, ultimo = voti → primo=7, centro=[5,8,6], ultimo=9.
Solution available after 3 attempts
Additional challenge
Given the tuple `point = (4, 5, 6)`, use unpacking to assign the three values to the variables `x`, `y`, `z` respectively. Then, calculate the sum of `x`, `y`, and `z` and store it in `coord_sum`. Finally, evaluate `coord_sum`.
Show hint
Use x, y, z = point to extract the three coordinates in a single statement.
Solution available after 3 attempts