Skip to course content
Free course

Python Foundations / Module 3 / Tuples and Unpacking

Module 3 lesson

Tuples and Unpacking

Unit ID: M03-U02 Estimated active time: 20-30 minutes

A tuple groups values in order

course_version = (1, 2, 0)
print(course_version[0])

Tuples are ordered and indexable, but they are immutable. You cannot replace an item by index.

course_version[0] = 2

This raises TypeError.

Use a tuple when the grouping has a fixed meaning and replacing individual positions should not be an ordinary operation.

The comma creates the tuple

A one-item tuple needs a trailing comma:

one_item = ("python",)
not_a_tuple = ("python")
print(type(one_item))
print(type(not_a_tuple))

The first is a tuple. The second is a string inside grouping parentheses.

Unpack meaningful positions

course_version = (1, 2, 0)
major, minor, patch = course_version
print(major)
print(minor)
print(patch)

Unpacking assigns each position to a clear name. The number of names must match the number of tuple items unless an extended unpacking pattern is used.

Returning several values

You will later see functions that appear to return several values. Python commonly groups them as a tuple, which can then be unpacked.

For now, practise with fixed supplied values:

module_range = (1, 10)
first_module, last_module = module_range
print(f"Modules {first_module} to {last_module}")

A tuple is not automatically safer inside

The tuple itself cannot have an item replaced, but it may contain a mutable object:

record = ("PY-01", ["python", "beginner"])
record[1].append("data")

The tuple still points to the same list, and that list can change. Immutability can be shallow.

Practice

Create a tuple containing a fictional course code, revision number, and status. Unpack it into three clear names and print a labelled summary. Then try to replace one tuple item and read the error.

Takeaway

Tuples provide ordered fixed grouping and clear unpacking. They do not make nested mutable values immutable. Next, we will use dictionaries when fields need meaningful labels instead of positions.