Tuples and sets · 1 / 16 Theory

Tuples: data that does not change

A tuple is an ordered sequence of values, like a list, but with a key difference: once created it cannot be modified. It is the ideal structure to group data that belongs together and must not change, such as the coordinates of a point or a date.

Creating tuples

point = (3, 4)
date = (2026, 11, 13)
name = ("Ana", "Garcia")
empty = ()

print(point)        # (3, 4)
print(type(point))  # <class 'tuple'>

The parentheses are optional: what really creates the tuple are the commas. That is why point = 3, 4 is the same as point = (3, 4).

A tuple with a single element

To create a tuple with a single value you must put a comma at the end. Without the comma, the parentheses are just parentheses:

a = (5,)
b = (5)

print(type(a))  # <class 'tuple'>
print(type(b))  # <class 'int'>

Accessing the elements

You access them just like in a list: with indexes (starting at 0, with negative ones counting from the end) and with slices.

date = (2026, 11, 13)

print(date[0])      # 2026
print(date[-1])     # 13
print(date[1:])     # (11, 13)
print(len(date))    # 3
print(11 in date)   # True

for value in date:
    print(value)

Tuples are immutable

If you try to change an element, Python raises an error:

date = (2026, 11, 13)
date[2] = 14
# TypeError: 'tuple' object does not support item assignment

If you need to "change" a tuple, you create a new one from the old one:

date = (2026, 11, 13)
new = date[:2] + (14,)
print(new)  # (2026, 11, 14)

Unpacking a tuple

You can spread the values of a tuple into variables in a single line. There must be as many variables as elements:

point = (3, 4)
x, y = point
print(x)  # 3
print(y)  # 4

year, month, day = (2026, 11, 13)
print(day)  # 13

This lets you swap the values of two variables without needing an auxiliary variable:

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

Returning several values from a function

When a function does return with several values separated by commas, it actually returns a tuple, and you can unpack it when calling it:

def min_max(numbers):
    return min(numbers), max(numbers)

smallest, largest = min_max([4, 9, 1, 7])
print(smallest, largest)  # 1 9

Lists of tuples

Tuples combine very well with lists: each tuple is a record and the list groups them. When sorting a list of tuples, Python compares the first element of each tuple first, and if they tie, the second one, and so on:

students = [(7, "Luis"), (9, "Ana"), (5, "Eva")]
students.sort(reverse=True)

for grade, name in students:
    print(f"{name}: {grade}")
# Ana: 9
# Luis: 7
# Eva: 5

Practice in Point on a plane, Minimum and maximum with a tuple and Student ranking.