Skip to content
Laviyx Learn

Try

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.

Beginner6 min readUpdated
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:

Python
point = (3, 4)
print(point[0], point[1], len(point))
Output
3 4 2

Indexing, 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:

Python
single = (5,)
not_tuple = (5)
print(type(single), type(not_tuple))
Output
<class 'tuple'> <class 'int'>

(5) is just the number 5 in brackets. A one-item tuple needs a trailing comma.

Tuples are immutable#

Python
point = (3, 4)
point[0] = 10
Output
TypeError: 'tuple' object does not support item assignment

You 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:

Python
x, y = (3, 4)
print(x, y)

name, age, city = ("Asha", 21, "Pune")
print(f"{name} is {age} and lives in {city}")
Output
3 4
Asha is 21 and lives in Pune

The number of variables must match the number of items. A starred name collects "the rest":

Python
first, *rest = (1, 2, 3, 4)
print(first, rest)
Output
1 [2, 3, 4]

Python's famous one-line swap is tuple unpacking in action:

Python
a, b = 1, 2
a, b = b, a
print(a, b)
Output
2 1

Returning several values from a function#

A function that returns a, b actually returns one tuple, which the caller can unpack:

Python
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))
Output
1 9
(1, 9) <class 'tuple'>

Looping over tuples#

Lists of tuples are a common way to store simple records:

Python
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])
Output
Asha: 92
Ravi: 85
Meera: 97
Top: Meera

key=lambda s: s[1] tells max to compare the scores. See Lambda Functions.

Tuple methods#

Because tuples cannot change, they have only two methods:

Python
colors = ("red", "green", "red", "blue")
print(colors.count("red"), colors.index("green"), "blue" in colors)
Output
2 1 True

Tuples as dictionary keys#

Dictionary keys must be immutable, so tuples can be keys and lists cannot:

Python
distances = {("Mumbai", "Pune"): 150, ("Delhi", "Agra"): 230}
print(distances[("Mumbai", "Pune")])
Output
150

Tuple or list?#

Use a tuple when…Use a list when…
the values are a fixed group (x, y), (name, age)you will add, remove or sort items
the data should not changethe size changes over time
you need a dictionary key or set memberitems are all the same kind of thing

Tuples are also slightly smaller and faster than lists, though that rarely decides the choice.

Python
lst = [1, 2, 3]
tup = tuple(lst)
print(tup, list(tup))
Output
(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
Python
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}")
Output
count=4 total=20 average=5.0

Key takeaway#

Finished this lesson?