Tuple Examples#
Note
Source: Python-specific — no direct equivalent in the C# edition. Examples draw on standard Python idioms for representing fixed-structure data such as coordinates, colours, and paired sequences.
Tuples as Records#
A tuple is a natural way to group a fixed number of related values when you do not need a full class:
# 2-D point
origin = (0, 0)
point = (3.0, -1.5)
# RGB colour
red = (255, 0, 0)
teal = (0, 128, 128)
# (name, grade) record
student = ("Alice", 91)
name, grade = student
print(f"{name} earned a {grade}")
Output:
Alice earned a 91
Tuples as Dictionary Keys#
Because tuples are immutable they can serve as dictionary keys — lists cannot:
# Map grid coordinates to a label
grid = {
(0, 0): "origin",
(1, 0): "east",
(0, 1): "north",
}
print(grid[(1, 0)])
Output:
east
This is useful for representing two-dimensional data, graph edges, or any pairing that should be looked up quickly.
Iterating Paired Data with zip()#
zip() pairs elements from multiple sequences into tuples, making it
easy to iterate over related data:
xs = [0, 1, 2, 3]
ys = [0, 1, 4, 9]
for x, y in zip(xs, ys):
print(f"({x}, {y})")
Output:
(0, 0)
(1, 1)
(2, 4)
(3, 9)
Building a List of Tuples#
A common pattern is building a list of tuples to represent tabular data:
import math
table = [(n, n**2, math.sqrt(n)) for n in range(1, 6)]
for n, sq, root in table:
print(f"{n:2d} {sq:4d} {root:.4f}")
Output:
1 1 1.0000
2 4 1.4142
3 9 1.7321
4 16 2.0000
5 25 2.2361
Sorting a List of Tuples#
sorted() compares tuples lexicographically by default (first element
first, then second, etc.):
students = [("Carol", 85), ("Alice", 91), ("Bob", 78)]
by_name = sorted(students)
by_grade = sorted(students, key=lambda s: s[1], reverse=True)
print(by_name)
print(by_grade)
Output:
[('Alice', 91), ('Bob', 78), ('Carol', 85)]
[('Alice', 91), ('Carol', 85), ('Bob', 78)]