What a tuple is
Some values belong together: a pet's name and age, or a point's x and y. A tuple keeps a few values like these in one variable. You write the values in parentheses, separated by commas, and read each one by its position, starting from 0.
pet = ("Rex", 4)
print(pet[0])
print(pet[1])
print(len(pet))
Rex
4
2
A tuple looks like a list, but it holds a fixed few values, often of different kinds (a str and an int here). A list holds many values of one kind, and it can grow.
Tuples show up whenever Python needs to hand back "a few things at once". A line such as pet[0] reads the first one, and negative positions work too: pet[-1] is the last value, here 4. Slicing and len behave as they do for lists, so what you know about indexing carries over.
Unpacking
Unpacking gives each value of a tuple its own name, in one line. The names go on the left of the =, in the same order as the values.
name, age = pet
print(name, age)
Rex 4
You need exactly one name per value. Three names for a two-value tuple stop the program with ValueError: not enough values to unpack (expected 3, got 2).
You have already unpacked tuples without calling them that: in for name, points in scores.items(), each key and value arrives as a tuple, and the loop splits it into two names.
Returning two values
A function can return a tuple: return a, b packs both values, and the caller unpacks them with x, y = f(). The parentheses are optional here, because the comma is what makes the tuple.
def firstAndLast(word):
return word[0], word[-1]
first, last = firstAndLast("code")
print(first, last)
c e
In a type hint, Tuple[str, int] means a tuple of a str and an int, in that order. It plays the same role as List[int] does for a list.
Tuples can't be changed
Assigning to a position stops with a TypeError:
pet[1] = 5
TypeError: 'tuple' object does not support item assignment
To change a value, build a new tuple: pet = (pet[0], 5) gives ('Rex', 5). One more trap: a one-value tuple needs a trailing comma. (5,) is a tuple, while (5) is just the integer 5 in parentheses.
Choosing between a tuple and a list
Ask what the value is. If it is "one pet" or "one point", a few parts with different jobs, use a tuple. If it is "all the pets", a collection whose size can change, use a list. Often you meet both: a list of tuples, such as [("Rex", 4), ("Bella", 7)], where each tuple is one pet and the loop for name, age in pets unpacks one pet per pass.
The exercise, step by step
The task has three parts, and the code already prints the three lines.
- Make
splitTimereturn the whole hours,minutes // 60, and the minutes left,minutes % 60. For 135 minutes that is 2 and 15. - Unpack
petintonameandage. - Call
splitTime(135)and unpack its result intohoursandmins.
def splitTime(minutes):
return minutes // 60, minutes % 60
pet = ("Rex", 4)
print(pet[0])
name, age = pet
print(name, "is", age)
hours, mins = splitTime(135)
print(name, "walked", hours, "h", mins, "min")
Rex
Rex is 4
Rex walked 2 h 15 min
Printing splitTime(135) directly shows (2, 15), which is one tuple.
Key takeaways
- A tuple groups a few values; read them with
t[0],t[1]. - Unpack with one name per value:
name, age = pet. return a, breturns a tuple, and the caller unpacks it.- A list of tuples is a common shape: loop over it and unpack each tuple in the
forline. - Tuples can't be changed; build a new one instead.
