Python course menu
Python Tuples: Immutable Sequences, Unpacking and When to Use Them
Learn Python tuples: creating tuples (including the one-item comma rule), indexing, immutability, tuple unpacking, returning several values from a function, tuples as dictionary keys, and tuples vs lists.
On this page
A tuple is an ordered collection, like a list, but immutable: once created, it cannot be changed. Tuples are perfect for small, fixed groups of related values, such as coordinates, a date, or a database row.
Creating tuples#
Write values separated by commas, usually inside parentheses:
point = (3, 4)
print(point[0], point[1], len(point))3 4 2Indexing, slicing, len(), in and looping work exactly as with lists.
The one-item tuple#
It is the comma that makes a tuple, not the parentheses:
single = (5,)
not_tuple = (5)
print(type(single), type(not_tuple))<class 'tuple'> <class 'int'>(5) is just the number 5 in brackets. A one-item tuple needs a trailing comma.
Tuples are immutable#
point = (3, 4)
point[0] = 10TypeError: 'tuple' object does not support item assignmentYou cannot add, remove or replace items. To "change" a tuple, create a new one (or convert to a list, change it, and convert back).
Unpacking#
Assign a tuple's items to several variables in one line:
x, y = (3, 4)
print(x, y)
name, age, city = ("Asha", 21, "Pune")
print(f"{name} is {age} and lives in {city}")3 4
Asha is 21 and lives in PuneThe number of variables must match the number of items. A starred name collects "the rest":
first, *rest = (1, 2, 3, 4)
print(first, rest)1 [2, 3, 4]Python's famous one-line swap is tuple unpacking in action:
a, b = 1, 2
a, b = b, a
print(a, b)2 1Returning several values from a function#
A function that returns a, b actually returns one tuple, which the caller can unpack:
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([4, 9, 1, 7])
print(low, high)
result = min_max([4, 9, 1, 7])
print(result, type(result))1 9
(1, 9) <class 'tuple'>Looping over tuples#
Lists of tuples are a common way to store simple records:
students = [("Asha", 92), ("Ravi", 85), ("Meera", 97)]
for name, score in students:
print(f"{name}: {score}")
best = max(students, key=lambda s: s[1])
print("Top:", best[0])Asha: 92
Ravi: 85
Meera: 97
Top: Meerakey=lambda s: s[1] tells max to compare the scores. See Lambda Functions.
Tuple methods#
Because tuples cannot change, they have only two methods:
colors = ("red", "green", "red", "blue")
print(colors.count("red"), colors.index("green"), "blue" in colors)2 1 TrueTuples as dictionary keys#
Dictionary keys must be immutable, so tuples can be keys and lists cannot:
distances = {("Mumbai", "Pune"): 150, ("Delhi", "Agra"): 230}
print(distances[("Mumbai", "Pune")])150Tuple or list?#
Tuples are also slightly smaller and faster than lists, though that rarely decides the choice.
lst = [1, 2, 3]
tup = tuple(lst)
print(tup, list(tup))(1, 2, 3) [1, 2, 3]Common mistakes#
Practice#
Practice exercise
Write a function stats(numbers) that returns the count, total and average of a list as a tuple. Unpack the result and print count=4 total=20 average=5.0 for [2, 4, 6, 8].
Show hint
return len(numbers), sum(numbers), sum(numbers) / len(numbers).
Show solution
def stats(numbers):
total = sum(numbers)
return len(numbers), total, total / len(numbers)
count, total, average = stats([2, 4, 6, 8])
print(f"count={count} total={total} average={average}")count=4 total=20 average=5.0Key takeaway#
Finished this lesson?