Python 101Free
DATA STRUCTURES

Tuples

Immutable, fixed shape records.

SECTION 01

The tuple model

Unlike a list, a tuple locks its shape at creation: you cannot add, remove, or replace elements. The shape is decided at creation time and cannot change. Trying to assign into a tuple raises TypeError. The only way to "modify" a tuple is to build a new one.

Use a tuple when position has meaning. A point is (x, y), a database row is (id, name, created_at), a return value with multiple parts is (result, error). The fixed shape is the point: it tells the reader the shape is part of the contract.

Because tuples are immutable, they are also hashable. This means you can use them as dictionary keys or as members of a set, which is something you cannot do with a list.

python
point = (3, 7)
# point[0] = 9       # TypeError: tuples are immutable

seen = {(3, 7), (0, 0)}   # tuples can live in a set
1 more section

Create a free account to access all sections and animations.

Create free accountAlready have an account? Sign in