After this lesson you can create tuples, take them apart into separate variables, and choose between a tuple and a list. If you understand lists, you already know most of what a tuple can do.
What a tuple is
A tuple is an ordered collection, just like a list. The difference is that once it is created it cannot change: you cannot add, remove or replace items. We say a tuple is immutable. A tuple is usually written with parentheses:
point = (3, 7)
shop = ("Corner Books", "Delhi", 2012)
empty = ()
print(point)
print(shop)
print(empty)
print(type(point))(3, 7)
('Corner Books', 'Delhi', 2012)
()
<class 'tuple'>You read tuple items the same way as list items, by index and by slice, and you can use len, in and for too:
print(shop[0])
print(shop[-1])
print(shop[1:])
print(len(shop))
print("Delhi" in shop)
for part in point:
print(part)Corner Books
2012
('Delhi', 2012)
3
True
3
7The parentheses are mostly for readability. It is the commas that build a tuple, so 1, 2, 3 is already a tuple:
colours = "red", "green", "blue"
print(colours)
print(type(colours))('red', 'green', 'blue')
<class 'tuple'>The one-item tuple
Because parentheses also group expressions, (5) is just the number 5. To make a tuple with a single item you need a trailing comma:
not_a_tuple = (5)
one = (5,)
print(type(not_a_tuple))
print(type(one))
print(one)<class 'int'>
<class 'tuple'>
(5,)This looks odd at first, but it is the only way Python can tell the two cases apart.
Tuples cannot be changed
Trying to change a tuple fails:
point = (3, 7)
point[0] = 10TypeError: 'tuple' object does not support item assignmentIf you need a different tuple, build a new one. You can combine tuples with +:
point = (3, 7)
moved = (10,) + point[1:]
print(moved)
print(point)(10, 7)
(3, 7)Tuples have only two methods, count and index, because nothing else makes sense for a fixed collection:
grades = ("A", "B", "A", "C", "A")
print(grades.count("A"))
print(grades.index("C"))3
3One detail: if a tuple holds a mutable item such as a list, that inner list can still change. The tuple fixes which objects it holds, not what is inside them.
box = ("label", [1, 2])
box[1].append(3)
print(box)('label', [1, 2, 3])Unpacking
The most useful thing about tuples is unpacking: copying each item into its own variable in one line.
point = (3, 7)
x, y = point
print(x)
print(y)
name, city, year = shop
print(name, "opened in", year)3
7
Corner Books opened in 2012The number of names must match the number of items:
a, b = (1, 2, 3)ValueError: too many values to unpack (expected 2)When you only want some of the items, put a star on one name and it collects the leftovers into a list:
first, *middle, last = (10, 20, 30, 40, 50)
print(first)
print(middle)
print(last)10
[20, 30, 40]
50Unpacking also gives the classic way to swap two variables without a temporary one:
a = 1
b = 2
a, b = b, a
print(a, b)2 1A function that wants to return several values does it by returning a tuple, and the caller unpacks it. divmod is a built-in example that returns the quotient and remainder together:
quotient, remainder = divmod(17, 5)
print(quotient, remainder)3 2Converting and choosing
tuple() turns any collection into a tuple, and list() turns a tuple back into a list:
print(tuple([1, 2, 3]))
print(list((1, 2, 3)))
print(tuple("abc"))(1, 2, 3)
[1, 2, 3]
('a', 'b', 'c')So when should you pick one? Use a tuple when the items form a fixed record where each position has a meaning, such as (latitude, longitude) or (name, price). Use a list when you have a number of similar items that may grow, shrink or be sorted. Because tuples cannot change, they are also safe to use as dictionary keys, which you will see later in the course:
stock = {("pen", "blue"): 40, ("pen", "red"): 15}
print(stock[("pen", "red")])15Common mistakes
- Forgetting the comma in a one-item tuple.
("x")is a string. - Trying to change a tuple. If you find yourself wanting to, you probably want a list.
- Unpacking the wrong number of items. The names on the left must match the length, or use a starred name.
- Thinking a tuple is deeply frozen. A list inside a tuple can still be changed.
- Using a tuple when order of growth matters. Building a result item by item is a job for a list.
Exercise
Create a tuple product = ("notebook", 45, 12) holding a name, a price and a stock count. Unpack it into three variables and print a sentence that uses all three. Then create a one-item tuple holding the name only.
Show one possible answer
product = ("notebook", 45, 12)
name, price, stock = product
print(name, "costs", price, "and we have", stock)
only_name = (name,)
print(only_name)notebook costs 45 and we have 12
('notebook',)Previous: List methods. Next: Sets.
Key points
- A tuple is an ordered collection written with parentheses, like a list, but it cannot be changed after creation.
- A one-item tuple needs a trailing comma: (5,). Without it the parentheses are just grouping.
- Unpacking assigns each tuple item to its own name: x, y = point. Star unpacking collects the rest.
- Use tuples for small fixed records such as coordinates or return values. Use lists for collections that grow or shrink.