Data Structures · Dictionaries and Sets · lesson 10 of 10
Tuples and unpacking
about 12 minutes · free · runs in your browser
Step 1 of 2
Fixed groups of values
A tuple is like a list that cannot be changed. Round brackets, or often no brackets at all:
point = (3, 4)
pair = 3, 4 # the same thing
single = (3,) # the comma is what makes it a tuple
Because they cannot change, tuples suit values that belong together and should stay that way — coordinates, RGB colours, a row from a table. They can also be dictionary keys, which lists cannot.
Unpacking pulls a tuple apart in one line:
x, y = point
name, age, city = person
The number of names has to match the number of values. This is also how you swap without a temporary variable:
a, b = b, a
Your turn: write min_max(numbers) returning the smallest and largest as a tuple.
Return None for an empty list.
You start from this, and edit it in the browser:
def min_max(numbers):
# Return (smallest, largest), or None if empty.
pass
Step 2 of 2
Returning several values
A function returning a tuple is Python's way of returning more than one thing, and the caller usually unpacks it straight away:
low, high = min_max(numbers)
Your turn: write split_name(full_name) returning (first, last). If there is
only one word, the last name should be an empty string.
You start from this, and edit it in the browser:
def split_name(full_name):
# Return (first, last).
pass