← Python from Scratch Lesson 38 of 78 · 10 XP

Tuples

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A tuple (tuple) is like a list, but immutable: once created, it can't be extended or changed. It is written in parentheses:

point = (3, 5)
point[0]          # 3
point[0] = 10     # TypeError

Why would you want an unchangeable list? To store data that must not change: coordinates, a date, a colour (255, 0, 0). Tuples can be used as dictionary keys; lists can't.

Their main superpower is unpacking:

x, y = point           # x = 3, y = 5
name, age = ("Roma", 20)

That's exactly how a function can return several values at once: in fact it returns one tuple.

def divide(a, b):
    return a // b, a % b     # the parentheses can be left out

q, r = divide(17, 5)         # q = 3, r = 2

Task. Write a function min_max(nums) that returns the tuple (minimum, maximum). You may not use the built-in min and max — go through the list with a loop.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.