Tuples in Python
A tuple is an ordered collection of values that cannot be changed after it is created. You write the values separated by commas, usually inside parentheses. It is read like a list, with indexes, slices and loops, but it has no append() and no item assignment. Tuples suit fixed groups of related values, such as a point or a record.
Key facts
point = (3, 4)creates a tuple. The commas make the tuple, and the parentheses are optional in most places.("apple",)is a one-item tuple, and("apple")is a string.- Tuples are indexed, sliced and looped over like lists, with
point[0]andlen(point). - Assigning to an item raises
TypeError: 'tuple' object does not support item assignment. x, y = pointunpacks a tuple into named variables.
What is a tuple in Python?
A tuple is an ordered collection of values that cannot be changed after it is created. You write the values separated by commas, usually inside parentheses, and Python keeps them in order like a list. Tuples suit a fixed group of related values, such as a point's x and y, a date's year, month and day, or a record with a name and an age.
point = (3, 4)
print(point)
print(type(point))
print(len(point))(3, 4) <class 'tuple'> 2
Everything you know about reading a list applies to a tuple. The difference is that a tuple has no append(), no remove() and no item assignment, so the values you put in are the values that stay. That makes a tuple safe to pass around and lets it serve as a key in a dictionary, as long as the values inside it can't change either. The dictionaries lesson covers keys.
How do I create a tuple in Python?
Write the values separated by commas, with or without parentheses. The commas make the tuple, so 3, 4 and (3, 4) are the same value, and a one-item tuple needs a trailing comma because ("apple") is only a string in parentheses. () is the empty tuple, and tuple() converts a list or any other iterable.
colors = "red", "green", "blue"
print(colors)
single = ("apple",)
print(type(single))
not_a_tuple = ("apple")
print(type(not_a_tuple))
empty = ()
print(empty)
print(tuple([1, 2, 3]))('red', 'green', 'blue')
<class 'tuple'>
<class 'str'>
()
(1, 2, 3)Python prints a tuple with parentheses even when you left them out. Write the parentheses yourself in any expression that has other commas nearby, such as a function call, so the tuple's boundaries are clear.
How do I access items in a tuple?
Use the same square brackets, slices, len(), in and for loops that work on a list. Indexes start at 0, negative indexes count from the end, and a slice of a tuple is itself a tuple.
days = ("Mon", "Tue", "Wed", "Thu")
print(days[0])
print(days[-1])
print(days[1:3])
print("Tue" in days)
for day in days:
print(day)Mon
Thu
('Tue', 'Wed')
True
Mon
Tue
Wed
ThuThe slice days[1:3] comes back as a tuple, in parentheses, because slicing gives you a piece of the same type you started with. Looping over a tuple visits its items in order, one per pass.
Can I change a tuple in Python?
No. Assigning to an index raises a TypeError, because a tuple is immutable, and there are no methods that add or remove items.
point = (3, 4)
point[0] = 10Traceback (most recent call last):
File "main.py", line 2, in <module>
point[0] = 10
~~~~~^^^
TypeError: 'tuple' object does not support item assignmentWhat you can do is build a new tuple and assign it to the same name. + joins two tuples into a new one, and a list inside a tuple can still be changed, because the tuple holds the list itself, not a copy of its contents.
point = (3, 4)
point = point + (5,)
print(point)
record = ("Ada", [90, 85])
record[1].append(70)
print(record)(3, 4, 5)
('Ada', [90, 85, 70])point + (5,) makes a new three-item tuple, and the old (3, 4) is thrown away. The second half shows that immutability stops at the tuple's own items. The tuple still holds the same list, and that list grew even though record itself never changed.
What is tuple unpacking in Python?
Unpacking assigns the items of a tuple to several variables in one statement. Write as many names on the left as the tuple has items, and Python hands each item to the name in the same position.
point = (3, 4)
x, y = point
print(x)
print(y)
a = 1
b = 2
a, b = b, a
print(a, b)
pairs = [("Ada", 36), ("Bob", 28)]
for name, age in pairs:
print(name, "is", age)3 4 2 1 Ada is 36 Bob is 28
Swapping two variables is the classic use, because the whole right side b, a is evaluated before either name is reassigned. The for loop unpacks each tuple in the list into name and age, the same trick you used in the for loops lesson with enumerate(), which hands out position and item pairs. The number of names must match the number of items, or Python raises ValueError.
What is the difference between a tuple and a list in Python?
A tuple cannot be changed after it is created, and a list can. Everything else about reading them is the same, so the choice comes down to whether the values form a fixed group or a collection that grows and shrinks.
| Type | Written as | Can it change? | Methods | Use it when |
|---|---|---|---|---|
| Tuple | Parentheses, (3, 4) | No, item assignment raises TypeError | count() and index() | The values form a fixed group, such as a coordinate or a record, or must serve as a dictionary key |
| List | Square brackets, [3, 4] | Yes, in place | Eleven, including append(), remove() and sort() | The collection will be added to, removed from or sorted |
A tuple written out in code is a little faster to build, and a tuple is a little smaller in memory, because Python knows its size will never change. That gain is rarely the reason to pick one. Pick a tuple because the values belong together and must not change, and a list because the collection will.
How do I convert between a tuple and a list?
Call list() on a tuple and tuple() on a list. Converting to a list is the usual way to edit a tuple's values, because you change the list and convert back. The two tuple methods, count() and index(), work as they do on a list.
scores = (7, 3, 7, 9)
as_list = list(scores)
as_list.append(1)
print(as_list)
print(tuple(as_list))
print(scores.count(7))
print(scores.index(9))[7, 3, 7, 9, 1] (7, 3, 7, 9, 1) 2 3
The conversions build new values, so scores itself is still the original four-item tuple at the end. count(7) found two sevens, and index(9) found the 9 at position 3.
Common mistakes with tuples in Python
These four mistakes with tuples are the common ones. Three stop the program with a message, and the first runs without complaint and gives a string where you expected a tuple.
- Forgetting the comma.
("apple")is the string"apple", andlen()reports 5 instead of 1. Write("apple",). - TypeError: 'tuple' object does not support item assignment. Code tried to change an item in place. Build a new tuple, or use a list when the values need to change.
- ValueError: too many values to unpack (expected 2, got 3). Two names were given for a three-item tuple. Match the number of names to the number of items, or index the items you need.
- AttributeError: 'tuple' object has no attribute 'append'. A tuple has no methods that add or remove items. Convert it to a list, or use a list from the start.
Run the two broken programs to see the messages, then fix them in the editor. The item assignment error has its own example under the heading about changing a tuple.
a, b = (1, 2, 3)Traceback (most recent call last):
File "main.py", line 1, in <module>
a, b = (1, 2, 3)
^^^^
ValueError: too many values to unpack (expected 2, got 3)point = (3, 4)
point.append(5)Traceback (most recent call last):
File "main.py", line 2, in <module>
point.append(5)
^^^^^^^^^^^^
AttributeError: 'tuple' object has no attribute 'append'Exercise
Unpack the three values in person into name, age and city, so the program prints Ada is 36 and lives in London. The starter unpacks into two names and stops with a ValueError.
person = ("Ada", 36, "London")
name, age = person
print(name, "is", age, "and lives in", city)
Ada is 36 and lives in London
Show the solution
person = ("Ada", 36, "London")
name, age, city = person
print(name, "is", age, "and lives in", city)
Quiz
This quiz has 5 questions. Pick an answer to see why it is right or wrong.
-
1What does this program print?
t = ("a") print(type(t))Parentheses alone do not make a tuple, so ("a") is the string "a". A trailing comma, as in ("a",), is what makes a one-item tuple.
-
2What happens when a program runs point[0] = 10 on the tuple point = (3, 4)?
A tuple does not support item assignment, so Python raises TypeError. Building a new tuple needs an expression such as (10,) + point[1:], never an assignment to an index.
-
3What does this program print?
a, b = (1, 2) print(b)Unpacking hands the first item to a and the second to b, so b is 2. Two names for a two-item tuple is a valid unpacking.
-
4Which of these can you not do with a tuple?
A tuple has no append(), because it cannot change after it is created. Indexing, looping and len() all work on tuples exactly as they do on lists.
-
5What does this program print?
print(len((1,)))(1,) is a tuple with one item, so its length is 1. Without the comma, (1) would be the number 1 and len() would raise a TypeError.