Learn Python / Tuples

Tuples

A tuple is like a list that can't be changed. Once you create it, its items stay exactly as they are. That makes tuples perfect for values that belong together and shouldn't change, such as a point's coordinates, an RGB colour or a date.

Creating a tuple

Write the items inside parentheses:

point = (3, 4)
color = (255, 128, 0)
person = ("Ada", 36, "London")

print(point)
print(person)
print(type(point))
Output

The parentheses are actually optional. It's the commas that make a tuple:

coordinates = 10, 20
print(coordinates)
print(type(coordinates))
Output

A tuple with one item needs a trailing comma, otherwise Python sees an ordinary value in brackets:

not_a_tuple = (5)
a_tuple = (5,)

print(type(not_a_tuple))
print(type(a_tuple))
Output

Reading items

Indexing, slicing, len() and in all work just like they do for lists:

days = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")

print(days[0])
print(days[-1])
print(days[:5])
print(len(days))
print("Sat" in days)
print(days.index("Wed"))
print(days.count("Mon"))
Output

Tuples can't be changed

Trying to change an item raises a TypeError:

point = (3, 4)
point[0] = 10
Output

There's also no append, remove or sort. If you need a changed version, build a new tuple:

point = (3, 4)
moved = (point[0] + 1, point[1])
print(moved)
Output
Going deeper: A tuple can hold a list optional

A tuple can't change which items it holds, but if one of those items is a list, the list itself can still change:

record = ("Ada", [90, 85])
record[1].append(77)

print(record)
Output

The tuple still holds the same list; it's the list's contents that changed. Because of this, a tuple that contains a list can't be used as a dictionary key or put in a set.

Unpacking

Unpacking assigns each item of a tuple to its own variable in one step:

person = ("Ada", 36, "London")
name, age, city = person

print(name)
print(age)
print(city)
Output

The number of variables must match the number of items:

point = (3, 4, 5)
x, y = point
Output
Going deeper: Collecting the rest with a star optional

Put * before one name to collect "everything else" into a list. Then the counts don't have to match:

scores = (98, 91, 85, 77, 60)
first, second, *rest = scores

print(first)
print(second)
print(rest)
Output

You've already seen unpacking at work when swapping two variables. a, b = b, a builds a tuple on the right and unpacks it on the left:

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

Returning several values

Some built-in functions give back a tuple. For example, divmod(a, b) gives both a // b and a % b at once, as a tuple. You can unpack the result straight away:

result = divmod(17, 5)
print(result)

quotient, remainder = divmod(17, 5)
print(quotient, remainder)
Output

You'll use this a lot once you write your own functions in Part 3.

Tuple or list?

Use a list when… Use a tuple when…
the items will change (add, remove, sort) the items are fixed
all items are the same kind of thing (a list of names) each position means something different (name, age, city)
the length varies the length is part of the meaning (an x, y point)

Tuples are also slightly faster and use less memory, and they can be used as dictionary keys (more on that in the next lesson), which lists can't.

Converting between them is easy:

numbers = [3, 1, 2]
frozen = tuple(numbers)
print(frozen)

editable = list(frozen)
editable.append(4)
print(editable)
Output
Going deeper: Named tuples optional

In a plain tuple you have to remember that person[1] is the age. A named tuple lets you use names instead, while still behaving like a tuple:

from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)

print(p)
print(p.x, p.y)     # by name
print(p[0])         # by index still works
x, y = p            # and so does unpacking
print(x + y)
Output

Named tuples are a lightweight step towards classes, which you'll meet in Part 5.

Exercises

Exercise 1: Unpack an RGB colour

Unpack the tuple into red, green and blue, then print R=255 G=165 B=0.

orange = (255, 165, 0)
Output

Exercise 2: Weekend check

Print True if today is in the weekend tuple.

weekend = ("Saturday", "Sunday")
today = "Sunday"
Output

Exercise 3: Hours and minutes

Use divmod() and unpacking to split 135 minutes into hours and minutes, then print 2 h 15 min.

total_minutes = 135
Output

Exercise 4: Distance between points

Each point is a tuple (x, y). Unpack both and print the distance between them, which is 5.0. The formula is √((x2 − x1)² + (y2 − y1)²).

import math

p1 = (1, 2)
p2 = (4, 6)
Output

Tuple methods at a glance

Tuples have only two methods, because they can't change. Most of the work is done by operators and built-in functions. Each example starts from t = ("a", "b", "a").

Method or operation What it does Example Result
count(x) How many times x appears t.count("a") 2
index(x) Position of the first x (ValueError if missing) t.index("b") 1
len(t) Number of items len(t) 3
x in t Is x in the tuple? "b" in t True
t + other Joins two tuples into a new one t + ("c",) ('a', 'b', 'a', 'c')
t * n Repeats the tuple n times t * 2 ('a', 'b', 'a', 'a', 'b', 'a')
t[i], t[a:b] Reads an item, or a slice as a new tuple t[1:] ('b', 'a')
sorted(t) The items sorted, as a list sorted(t) ['a', 'a', 'b']
tuple(items) Makes a tuple from another collection tuple([1, 2]) (1, 2)

Summary

  • A tuple is an ordered, unchangeable sequence: (1, 2, 3).
  • Commas make the tuple. A single item needs a trailing comma: (5,).
  • Index, slice and search tuples just like lists.
  • Unpacking assigns items to variables: name, age = person.
  • Use tuples for fixed groups of related values, and lists for collections that change.