Python Arena
Step 3 of 3

Tuples without parentheses

It's the commas that make a tuple, not the parentheses. Values separated by commas are a tuple even without them:

In the Python interpreter
>>> numbers = 1, 2, 3
>>> numbers
(1, 2, 3)
>>> single = 5,
>>> single
(5,)

A tuple of one value needs its comma too: (5) is just the number 5 in parentheses.

Returning several values

A function returns one value, but that value can be a tuple. So a function can give back several values by returning them separated by commas:

def to_minutes(total_seconds: int) -> tuple:
    return total_seconds // 60, total_seconds % 60


result = to_minutes(135)
print(result)

minutes, seconds = to_minutes(135)
print(f"{minutes} min {seconds} s")
Output
(2, 15)
2 min 15 s

Unpacking

minutes, seconds = to_minutes(135) is called unpacking: the values of the tuple on the right go into the variables on the left, in order. The number of variables has to match the number of values:

point = (3, 7, 1)
x, y = point
Python stops with
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    x, y = point
    ^^^^
ValueError: too many values to unpack (expected 2, got 3)

Unpacking works in a for loop too. A loop over a list of tuples can unpack each one right away. That's what happens in for key, value in d.items(): items() gives each pair of the dictionary as a tuple.

pioneers = [("Ada", 1815), ("Alan", 1912), ("Grace", 1906)]
for name, year in pioneers:
    print(name, year)

ages = {"Ada": 36, "Max": 41}
print(list(ages.items()))
Output
Ada 1815
Alan 1912
Grace 1906
[('Ada', 36), ('Max', 41)]

Swapping two values

To swap the values of two variables, you would normally need a helper variable, because the first assignment overwrites one of the values:

helper = a
a = b
b = helper

With a tuple it takes one line. Python first makes a tuple of the values on the right, and only then unpacks it into the variables on the left:

a = 1
b = 2
a, b = b, a
print(a, b)
Output
2 1

Your task

Challenge 1 of 3

Fill in the blank so the loop unpacks each tuple into the variables name and score, and the program prints:

Ada: 92 points
Max: 78 points
Lin: 85 points

Challenge 2

Write a function share(amount, people) that shares amount sweets equally between people people. It returns two values: how many whole sweets each person gets, and how many are left over.

For example, share(17, 5) returns (3, 2): everyone gets 3, and 2 are left.

Challenge 3

Write a function best_and_worst(results) that takes a list of (name, score) tuples and returns two values: the name with the highest score and the name with the lowest score. No two scores are the same.

For example, best_and_worst([("Ada", 92), ("Max", 78), ("Lin", 85)]) returns ('Ada', 'Max').