Tuples¶
~15 min ยท prerequisite: Lists
What you will be able to do¶
- Create a tuple and read its items by index, the same way you read a list.
- Explain why a tuple cannot be changed, and choose between a list and a tuple.
- Use unpacking to give several names to the items of a tuple in one line, including the swap
a, b = b, a.
The idea¶
A tuple is an ordered collection of values, like a list, but it is immutable. Once you create a tuple, you cannot add, remove, or replace an item. A tuple is written with parentheses, such as (3, 4), and its items are separated by commas. Parentheses are optional in many places, so point = 3, 4 also creates a tuple. Read the tuple by index exactly as you read a list: point[0] is 3.
The commas make the tuple, not the parentheses. A single item needs a trailing comma. The expression (5) is just the integer 5, and (5,) is a tuple with one item. Writing type((5,)) shows <class 'tuple'>.
Tuples are used when a group of values belongs together and should not change. For example, a pair (x, y) describes one point, and a row ("Ada", 36) describes one person. A list suits a collection that grows or shrinks, such as a shopping list. The choice also tells a reader something. A tuple says "these values form one fixed record".
The most useful tuple feature is unpacking. When you write x, y = point, Python takes the first item and stores it in x, and the second item goes to y. The number of names on the left must match the number of items on the right. Unpacking also gives you the swap. The line a, b = b, a first builds the tuple (b, a) from the old values, then unpacks it into the two names. No temporary variable is needed.
Tuples support len, in, for, and the methods count and index. The method count(x) returns how many items equal x, and index(x) returns the position of the first one.
Worked example¶
point = (3, 4)
print(point[0])
print(len(point))
x, y = point
print("x is", x, "and y is", y)
a = 10
b = 20
a, b = b, a
print(a, b)
single = (5,)
print(type(single))
print(type((5)))
Line by line, this is what Python does:
pointholds the tuple(3, 4).point[0]reads the first item, which is3.len(point)counts two items.x, y = pointunpacks the tuple. Nowxis3andyis4.a, b = b, abuilds the tuple(20, 10)from the old values and unpacks it, soabecomes20andbbecomes10.(5,)is a tuple with one item, sotypereportstuple. The expression(5)has no comma, so the parentheses are only grouping, andtypereportsint.
The output is:
Try it¶
The first block checks reading and unpacking. The second block checks the trailing comma and the swap. The third block checks the methods count and index.
Common mistakes¶
-
Trying to change an item. The code
point = (3, 4)followed bypoint[0] = 9gives:Create a new tuple instead, such as
point = (9, point[1]). If you need to change items often, use a list. -
Forgetting the comma in a one-item tuple. The code
value = (5)followed byvalue[0]gives:Write
value = (5,)with a trailing comma. -
Unpacking with the wrong count. The code
x, y = (1, 2, 3)gives:The number of names on the left must match the number of items on the right.
-
Unpacking a number. The code
x, y = 5gives:Only collections such as tuples and lists can be unpacked. Check the type of the value on the right.
Practice¶
- Create
city = ("Paris", 2161). Use indexing to assert thatcity[0]is"Paris", and assert thatlen(city)is 2. - Create
pair = (7, 9). Unpack it intoleftandright, then assert thatleft + rightequals 16. - Create
letters = ("a", "b", "a", "c"). Assert thatletters.count("a")is 2 and thatletters.index("c")is 3. - Create
one_item = ("hello",). Assert thattype(one_item)istupleand thatlen(one_item)is 1. - Stretch: start with
x = 1andy = 2, and a tuplecoords = (x, y). Swap the values ofxandywith a single unpacking line, then assert thatcoordsstill equals(1, 2)and thatxis now 2 andyis now 1.
Solution
-
python city = ("Paris", 2161) assert city[0] == "Paris" assert len(city) == 2 -
python pair = (7, 9) left, right = pair assert left + right == 16 -
python letters = ("a", "b", "a", "c") assert letters.count("a") == 2 assert letters.index("c") == 3 -
python one_item = ("hello",) assert type(one_item) is tuple assert len(one_item) == 1 -
python x = 1 y = 2 coords = (x, y) x, y = y, x assert coords == (1, 2) assert x == 2 assert y == 1
Recap¶
- A tuple is an immutable, ordered sequence. Its items are read by index, but they cannot be changed.
- The comma makes a tuple. A one-item tuple needs a trailing comma, as in
(5,). - Unpacking, such as
a, b = b, a, gives names to the items in one line and makes swaps straightforward.