Python Tuples
A tuple is an ordered collection that cannot be changed after it is created. Use tuples for fixed groups of values, such as coordinates, RGB colours or a database row, and to return several values from a function.
- Create tuples, including one-item tuples
- Access items by index and slice
- Unpack a tuple into variables
- Know when a tuple beats a list
Create a tuple
Write items separated by commas, usually inside round brackets.
point = (12.5, 77.3)rgb = (255, 128, 0)mixed = ("Asha", 29, True)empty = () print(point, type(point).__name__)print(len(mixed), len(empty))(12.5, 77.3) tuple 3 0
The commas make the tuple, not the brackets. You can even leave the brackets out:
version = 3, 12, 1print(version)(3, 12, 1)
The one-item trap
A single value in brackets is just that value. Add a trailing comma to make a one-item tuple:
not_a_tuple = (5)one_item = (5,)print(type(not_a_tuple).__name__, type(one_item).__name__)int tuple
Access items
Indexing and slicing work exactly as with lists and strings, and a slice of a tuple is a new tuple.
days = ("Mon", "Tue", "Wed", "Thu", "Fri")print(days[0], days[-1])print(days[1:4])print("Wed" in days) for i, day in enumerate(days, 1): print(i, day, end=" ")Mon Fri
('Tue', 'Wed', 'Thu')
True
1 Mon 2 Tue 3 Wed 4 Thu 5 Fri Tuples are immutable
You cannot add, remove or replace items. Trying to raises a TypeError:
rgb = (255, 128, 0)rgb[0] = 200Traceback (most recent call last):
File "main.py", line 2, in <module>
rgb[0] = 200
~~~^^^
TypeError: 'tuple' object does not support item assignmentTo “change” a tuple, build a new one:
rgb = (255, 128, 0)rgb = (200,) + rgb[1:]print(rgb)print(rgb * 2)(200, 128, 0) (200, 128, 0, 200, 128, 0)
A tuple can contain a mutable object such as a list, and that list can still change. The tuple itself still holds the same objects, so it is called “shallowly” immutable.
Unpacking
Assign a tuple’s items to several names in one step. This is used everywhere in Python.
name, age, city = ("Ravi", 31, "Pune")print(name, age, city) first, *middle, last = (1, 2, 3, 4, 5)print(first, middle, last) def min_max(values): return min(values), max(values) # returns a tuple low, high = min_max([7, 2, 9, 4])print(low, high)Ravi 31 Pune 1 [2, 3, 4] 5 2 9
Tuple methods
Because tuples cannot change, they have only two methods:
marks = (90, 75, 90, 60, 90)print(marks.count(90))print(marks.index(75))print(sorted(marks), min(marks), max(marks), sum(marks))3 1 [60, 75, 90, 90, 90] 60 90 405
Tuples as dictionary keys
Tuples can be dictionary keys and set members because they are immutable (and hashable). Lists cannot.
distances = {("Pune", "Mumbai"): 150, ("Pune", "Nashik"): 210}print(distances[("Pune", "Mumbai")])150
bad = {["Pune", "Mumbai"]: 150}Traceback (most recent call last):
File "main.py", line 1, in <module>
bad = {["Pune", "Mumbai"]: 150}
^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')Named tuples
collections.namedtuple gives each position a name, so code reads p.x instead of p[0]:
from collections import namedtuple Point = namedtuple("Point", ["x", "y"])p = Point(3, 4)print(p)print(p.x, p.y, p[0])Point(x=3, y=4) 3 4 3
Check your understanding
Predict the output
t = (1, [2, 3], 4)t[1].append(99)print(t, len(t))(1, [2, 3, 99], 4) 3
The tuple still holds the same three objects, but the list inside it is mutable, so appending to it works.
Quick quiz
1. Which of these is a tuple with one item?
The trailing comma makes it a tuple.
2. How many methods does a tuple have?
Tuples cannot change, so methods like append() do not exist.
3. Can a tuple be a dictionary key?
Immutable tuples of hashable items are hashable.
Exercise: student records
Each record is a (name, marks) tuple. Print the topper and the class average, using unpacking in the loop.
[("Asha", 88), ("Ravi", 74), ("Meena", 93)]Topper: Meena 93 Average: 85.0
Hint 1
max(records, key=lambda r: r[1]) finds the record with the highest marks.
records = [("Asha", 88), ("Ravi", 74), ("Meena", 93)] total = 0for name, marks in records: total += marks top_name, top_marks = max(records, key=lambda r: r[1])print("Topper:", top_name, top_marks)print("Average:", round(total / len(records), 2))Topper: Meena 93 Average: 85.0
The for line unpacks each tuple. max() with a key compares records by their second item and returns the whole tuple, which is unpacked again.
Program Practice
70 Python Tuple Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Python tuples FAQ
What is the difference between a list and a tuple in Python?
A list is mutable and written with [ ]; a tuple is immutable and written with ( ). See List vs Tuple for a full comparison.
How do I create a tuple with one element?
Add a trailing comma: t = (5,) or just t = 5,.
Can I add an element to a tuple?
Not in place. Create a new tuple: t = t + (new_item,).
How do I convert a list to a tuple?
Use tuple(my_list). Use list(my_tuple) to go the other way.
1 thought on “Python Tuples”