Skip to content

Exercises — Tuples

Write a function that takes a list of (name, score) tuples and returns the name of the highest scorer.

results = [("Alice", 95), ("Bob", 87), ("Carol", 92)]
# expected: "Alice"

▶ Try in Playground

Use tuple unpacking to swap two variables a and b in a single line, then return them as (b_original, a_original).

a, b = 10, 20
# after swap: a=20, b=10
# return: (20, 10)

▶ Try in Playground

Define a namedtuple called Rectangle with fields width and height. Write a function area(rect) and a function perimeter(rect) that work with it.

r = Rectangle(width=5, height=3)
area(r) # 15
perimeter(r) # 16

▶ Try in Playground

Given a list of (city, temperature) tuples, return a new list sorted by temperature descending, with ties broken alphabetically by city name ascending.

data = [("Rome", 28), ("Oslo", 12), ("Madrid", 35), ("Athens", 35)]
# expected: [("Athens", 35), ("Madrid", 35), ("Rome", 28), ("Oslo", 12)]

▶ Try in Playground

Write a function unzip(pairs) that takes a list of 2-tuples and returns two separate tuples — one with all first elements, one with all second elements. Do not use zip(*pairs).

pairs = [(1, "a"), (2, "b"), (3, "c")]
# expected: (1, 2, 3), ("a", "b", "c")

▶ Try in Playground