Tuples
A tuple is an ordered collection that cannot be changed after it is created. Think of it as a list that is locked. Tuples are used for fixed groups of related values, such as a coordinate or a database row.
Creating a tuple
point = (3, 4)
rgb = (255, 128, 0)
single = (5,) # the comma makes it a tuple
also_tuple = 1, 2, 3 # parentheses are optional
empty = ()
print(point, rgb, single, also_tuple, empty)
print(type(single))(5) without a comma is just the number 5 in parentheses.
Accessing items
Indexing and slicing work exactly like lists.
rgb = (255, 128, 0)
print(rgb[0], rgb[-1])
print(rgb[1:])
print(len(rgb))Tuples are immutable
point = (3, 4)
try:
point[0] = 10
except TypeError as e:
print("Error:", e)If you need to change it, build a new tuple, or convert to a list and back:
point = (3, 4)
temp = list(point)
temp[0] = 10
point = tuple(temp)
print(point)Unpacking
Assigning a tuple to several names is the most common way tuples are used.
point = (3, 4)
x, y = point
print(x, y)
name, age, city = ("Tara", 23, "Pune")
print(f"{name} ({age}) lives in {city}")Functions that return several values are actually returning one tuple:
def min_max(values):
return min(values), max(values)
lo, hi = min_max([4, 9, 1, 7])
print(lo, hi)Looping and searching
colours = ("red", "green", "blue")
for c in colours:
print(c)
print("green" in colours)
print(colours.index("blue"))
print(colours.count("red"))index and count are the only two methods tuples have.
Why use a tuple instead of a list
- Safety. A tuple cannot be modified by accident somewhere else in the program.
- Dictionary keys. Tuples can be dictionary keys and set members; lists cannot.
- Speed and memory. Tuples are slightly lighter than lists.
- Meaning. A tuple says "these values belong together as one thing"; a list says "here is a collection of similar things".
locations = {(28.6, 77.2): "Delhi", (19.1, 72.9): "Mumbai"}
print(locations[(28.6, 77.2)])Named tuples
When positions get hard to remember, namedtuple gives each field a name while keeping it a tuple.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y, p)For anything more elaborate, see dataclasses in the type hints lesson.
Practice
- Create a tuple for a book with title, author and year. Unpack it into three variables and print a sentence.
- Write a function that returns both the sum and the average of a list, then unpack the result.
- Try adding a list as a dictionary key and read the error message. Then use a tuple instead.
