Collections
Tuples
Use a tuple for a fixed-size record where each position has a known meaning. Unpacking turns those positions into names at the point of use.
Source
point = (3, 4)
x, y = point
print(x + y)Output
7Tuples are sequences, so indexing and len() work. They are different from lists because their length and item references are fixed after creation.
Source
red = (255, 0, 0)
print(red[0])
print(len(red))Output
255
3Tuples pair naturally with multiple return values and unpacking. If the fields need names everywhere, graduate to a dataclass or named tuple.
Source
record = ("Ada", 10)
name, score = record
print(f"{name}: {score}")Output
Ada: 10Lists and tuples carry different intent. A list holds a variable number of similar items and grows with append; a tuple has a fixed shape where each position has its own meaning, and unpacking gives those positions names.
Source
scores = [10, 9, 8]
scores.append(7)
print(scores)
student = ("Ada", 2024, "math")
name, year, subject = student
print(name, year, subject)Output
[10, 9, 8, 7]
Ada 2024 mathNotes
- Tuples are immutable sequences with fixed length.
- Use tuples for small records where position has meaning.
- Use lists for variable-length collections of similar items.
- Reach for a dataclass or
NamedTuplewhen fields deserve names everywhere they're used.
See also
- related: Lists
- related: Unpacking
- next depth: Structured Data Shapes
Run the complete example
Expected output
7
255
3
Ada: 10
[10, 9, 8, 7]
Ada 2024 math
Execution time appears here after you run the example.