Tuples and records

Lesson 37 of 54 · Python Foundations

A tuple is an ordered sequence whose item references cannot be reassigned after creation. It is useful for a small group with a known structure, such as a location’s name and elevation.

site = ("Ridge", 420)
name, elevation = site
print(site[0], elevation)
print(name)
print(("solo",))
Ridge 420
Ridge
('solo',)

The comma makes a one-item tuple; ("solo") is just a parenthesized string. Unpacking assigns each item to a name in order, and the number of names must match the number of items in this form. Tuples support indexing and slicing like lists, but site[0] = "Valley" raises TypeError.

A function returning comma-separated values returns a tuple, which the caller can unpack. A list can hold several such records:

def limits(values):
    return min(values), max(values)

low, high = limits([4, 9, 2])
observations = [("north", 4), ("south", 9)]
print(low, high)
print(observations[1][0])
2 9
south

The first index chooses a tuple from the list; the second chooses a field within it. Tuple immutability is shallow: a tuple can contain a list, and that inner list can still change. Choose a list for a sequence that must be edited; choose a tuple for a fixed grouping.