Skip to content
FollowtheDamnCode

Tuples

Fixed groups of values, and unpacking them.

4 minute read

Big idea

A tuple is like a list that can't be changed. Use one for a small, fixed group of values that belong together — a point (x, y), a date, a name and an age.

Making a tuple

Tuples use round brackets (or just commas):

A tuple of values
point = (3, 4)
person = ("Ada", 36)
print(point[0], point[1])
print(len(person))
print(type(point))
output
3 4
2
<class 'tuple'>

Run and edit it in the app.

Reading works just like a list: indexing, slicing, len, in, looping.

Can't be changed

Fix the bug: move the point to (10, 4)
point = (3, 4)
point[0] = 10
print(point)
output
(10, 4)

Run and edit it in the app.

Tuples are immutable — point[0] = 10 raises a TypeError. Make a new tuple instead: point = (10, point[1]).

That's the point of a tuple: a value that can't change by accident, the way a list can when it's shared.

Unpacking

Pull a tuple apart into separate names in one line:

Predict: unpack and swap
person = ("Grace", 85)
name, age = person
print(name)
print(age)

a, b = 1, 2
a, b = b, a
print(a, b)
What does it print? Show the answer
Grace
85
2 1

Run and edit it in the app.

a, b = b, a is the Python way to swap two variables — no temporary variable needed. The right side builds the tuple (2, 1) first, then it's unpacked into a and b.

Returning several values

Tuples are how a function hands back more than one result (you'll write functions soon):

lowest, highest = min(scores), max(scores)
quotient, remainder = divmod(17, 5)    # (3, 2)

A one-item tuple needs a comma

The comma makes the tuple
not_a_tuple = (5)
a_tuple = (5,)
print(type(not_a_tuple))
print(type(a_tuple))
output
<class 'int'>
<class 'tuple'>

Run and edit it in the app.

List or tuple?

  • List — a collection that grows or changes: tasks, scores, search results.
  • Tuple — a fixed record: coordinates, RGB colours, a (name, score) pair.

x, y = 5, 9 then x, y = y, x. What are x and y?

Watch it

Think of it like

A list is a notebook you keep writing in. A tuple is a printed ticket: seat 14, row F, 7:30pm — fixed once it's issued.

Key terms

  • Tuple — An ordered, unchangeable collection: (1, 2).
  • Unpacking — Assigning the items of a tuple to several names at once.
  • Immutable — Can't be changed after it's made.

Check yourself

What's the main difference between a tuple and a list?

Which of these is a one-item tuple?

name, age = ('Ada', 36). What is age?