3.2. Tuples#

Amanda R. Kube Jotte

Sometimes, we want a collection of elements, but we don’t need that collection to be mutable. Tuples are similar to lists in that they are an ordered, indexed sequence of values and can contain multiple data types.

Creating Tuples and Immutability#

To create a tuples, we use parentheses () instead of square brackets (as a list would use). We still separate the elements using commas.

my_tuple = (1, 2, 3)
my_tuple
(1, 2, 3)
my_other_tuple = ("Robert Frost","The Road Not Taken")
my_other_tuple
('Robert Frost', 'The Road Not Taken')
a_third_tuple = (7.5, "bananas")
a_third_tuple
(7.5, 'bananas')

Note

If, for some reason, you want to create a tuple with only one value inside, the following code will not work:

my_tuple = (5)

Instead, you will need to add a comma after the value:

my_tuple = (5,)

Once created, tuples cannot be changed. They are immutable. That means there is no append() or insert() method that acts on a tuple. We also can’t reassign items in a tuple. Trying to do so will raise a TypeError.

my_tuple[0] = 99
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[4], line 1
----> 1 my_tuple[0] = 99

TypeError: 'tuple' object does not support item assignment

We don’t use tuples often in this book, but they can be useful when we have a fixed collection of objects or values (perhaps latitude and longitude or RGB values) or when we want to prevent a set of values from being accidentally modified.

Unpacking Tuples#

You might also see tuples as the output of functions. If you want a function to return multiple objects, you can return a tuple containing those objects. Later, you can get those items out of the tuple by indexing…

my_tuple[2]
3

…or by unpacking the tuple.

point = (3, 4)
x, y = point

print(x)
print(y) 
3
4

Tuples are useful when we want to keep values together in a fixed, ordered way — for example, (latitude, longitude) or (first_name, last_name).

But sometimes, we want a clearer way to associate one piece of information with another, so we can look it up quickly. Instead of just grouping values together in order, we can pair them with labels.

In the next section, we will learn about a way to store data as key–value pairs, so we can use a meaningful key (like a name) to retrieve the corresponding value (like a phone number).