Python Tuples · Exercises
Beginner

Python Tuples Exercises

4 exercises that build on the Python Tuples lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A tuple is an ordered collection of values, like a list, except that it is immutable: once created, its items cannot be changed, added or removed. By the end you can create and index tuples, unpack them into separate variables, return several values from a function, and decide when a tuple suits better than a list. You will practise: Unpack a book record; Predict: brackets or commas?; Fix the high-score update; Return three results.

0 / 4 completed

Python Tuples practice exercises

1. Unpack a book record

Write code Easy

Unpack the tuple book into three variables called title, author and year in one line, then print them as:

Dune by Frank Herbert (1965)
Your code
book = ("Dune", "Frank Herbert", 1965)

# unpack book here, then print the sentence

2. Predict: brackets or commas?

Predict the output Medium

Read the code and type exactly what it will print. Then press Check to run it and compare.

Read this code
a = (5)
b = (5,)
c = 1, 2, 3
print(type(a).__name__, type(b).__name__)
print(len(b), len(c))
x, y, z = c
print(z, y, x)

3. Fix the high-score update

Fix the bug Medium

The last high score should be replaced with 110, giving (120, 95, 110), but the code crashes with a TypeError. Fix it so that high_scores is still a tuple with the new value.

Your code
high_scores = (120, 95, 80)
high_scores[2] = 110
print(high_scores)

4. Return three results

Write code Hard

Write a function stats(numbers) that returns a tuple of three values: the smallest number, the largest number and the average. Then unpack stats(marks) into low, high and average and print them.

For example, stats([2, 4, 6]) returns (2, 6, 4.0).

Your code
marks = [64, 89, 72, 95]

def stats(numbers):
    # return smallest, largest and average
    pass

# unpack stats(marks) into low, high and average, then print them

Next lessonPython Unpacking

More Python Tuples examples · All Python exercises