A tuple is an ordered collection, like a list, that cannot be changed after it is created. That fixed nature makes tuples a good fit for data that belongs together and should stay that way: a pair of coordinates, a date, a database row. This lesson covers creating tuples, unpacking them, their two methods, and when to choose a tuple over a list.
In this lesson you will learn
- How to create tuples, including the one-item tuple trap
- Indexing, slicing and unpacking
- Why tuples are immutable and why that is useful
- The
count()andindex()methods - Tuples vs lists
Creating and Unpacking Tuples
point = (3, 4)
print(point[0], point[-1])
single = (5,) # the comma makes it a tuple
not_tuple = (5)
print(type(single).__name__, type(not_tuple).__name__)
x, y = point # unpacking
print("x =", x, "y =", y)
a, b = 1, 2
a, b = b, a # swap using tuples
print(a, b)
try:
point[0] = 10
except TypeError as e:
print("Error:", e)
Output
3 4
tuple int
x = 3 y = 4
2 1
Error: 'tuple' object does not support item assignment
- Indexing works as it does for lists:
point[0]is the first item,point[-1]the last. - The comma makes the tuple, not the brackets.
(5,)is a tuple;(5)is just the number 5 in brackets. - Unpacking assigns each item to its own variable:
x, y = point. a, b = b, aswaps two values, using a tuple behind the scenes.- Trying to change an item raises a
TypeError.
Methods, Slicing and Tuples as Keys
colors = ("red", "green", "blue", "green")
print(colors.count("green"), colors.index("blue"))
print(colors[1:3])
print("red" in colors)
# tuples can be dictionary keys, lists cannot
distance = {("Dhaka", "Sylhet"): 245, ("Dhaka", "Khulna"): 270}
print(distance[("Dhaka", "Sylhet")])
first, *rest = (10, 20, 30, 40)
print(first, rest)
record = ("Nabil", 23)
name, age = record
print(f"{name} is {age}")
Output
2 2
('green', 'blue')
True
245
10 [20, 30, 40]
Nabil is 23
- Tuples have just two methods:
count()andindex(). Anything that would change the tuple, likeappendorsort, does not exist. - Slicing returns a new tuple.
- Because tuples cannot change, they can serve as dictionary keys, which a list never can.
first, *rest = ...puts the first item infirstand collects the rest into a list.
Tuple or List?
| Tuple | List | |
|---|---|---|
| Syntax | (1, 2, 3) | [1, 2, 3] |
| Can change? | No | Yes |
| Usable as a dict key? | Yes (if its items are immutable) | No |
| Typical use | A fixed record: coordinates, RGB colour, a row | A growing collection of similar items |
| Memory | Slightly smaller | Slightly larger |
You can convert between them with tuple(my_list) and list(my_tuple). See Python Lists for the mutable version.
Common Mistakes
- Forgetting the comma in a one-item tuple.
- Unpacking into the wrong number of variables.
a, b = (1, 2, 3)raisesValueError; usea, *bfor the extra items. - Assuming everything inside is frozen. A tuple holding a list cannot swap the list for another object, but the list itself can still change.
Practice Exercises
Exercise 1. Given dob = (2004, 8, 15), unpack it and print 15/8/2004.
Show answer
year, month, day = (2004, 8, 15)
print(f"{day}/{month}/{year}")
Exercise 2. “Add” 4 to the tuple (1, 2, 3).
Show answer
Tuples cannot change, so create a new one: t = (1, 2, 3) + (4,) gives (1, 2, 3, 4).
Frequently Asked Questions
Why use a tuple if a list can do everything?
A tuple tells readers the data will not change, protects it from accidental edits, and can be used as a dictionary key or set item.
Is a tuple faster than a list?
Tuples are slightly faster to create and use a little less memory, but the difference rarely matters. Choose based on whether the data should change.
Summary
- Tuples are ordered and immutable; the comma creates them.
- Unpacking assigns each item to its own variable in one line.
- Only
count()andindex()are available. - Use tuples for fixed records and dictionary keys, and lists for collections that change.
Next: Python Sets.
