BYU logo Computer Science

Tuples

A tuple is a collection of one or more values, designated with parentheses:

student = ('Emma Johns', 22, 'political science')

In this case, the values might represent a student’s name, age, and major.

Tuples are immutable

A tuple is not mutable (changeable). In other words, it is immutable (not changeable).

Remember, we can change a list by appending something to it:

names = ['Anna', 'Angela']
names.append('Amy')

However, we cannot change a tuple. If we try:

student = ('Emma Johns', 22, 'political science')
student.append('3.92')

then we get an error:

Traceback (most recent call last):
  File "/Users/zappala/Documents/cs110/tuples.py", line 8, in <module>
    student.append('3.92')
AttributeError: 'tuple' object has no attribute 'append'

Unpacking

Let’s imagine we want to be able to print some information about a student. We could access each part of the tuple using index notation, like with a list:

student = ('Emma Johns', 22, 'political science')

print(f'{student[0]} is {student[1]} years old and a {student[2]} major')

This would print:

Emma Johns is 22 years old and a political science major

However, this is fairly unfriendly. It can be hard to look at that code and understand what student[1] is supposed to be.

Unpacking a tuple into separate variables makes this a lot cleaner:

name, age, major = ('Emma Johns', 22, 'political science')
print(f'{name} is {age} years old and a {major} major')

We now have three separate variables, name, age, and major instead of just student.

Returning multiple values

Tuples are particularly helpful for returning multiple values from a function. This function sorts two values, a and b, returning the values in sorted order:

def sorted_order(a, b):
    """Return a and b in ascending order"""
    if a < b:
        return a, b
    else:
        return b, a

Notice that we can often leave off the parentheses when returning values from a function.

We can call this function:

first, second = sorted_order(4, 2)
print(f'First comes {first}, then comes {second}')

And this will print:

First comes 2, then comes 4

In fact, this function will work with strings as well. We can call it as:

first, second = sorted_order('Amy', 'Angela')
print(f'First comes {first}, then comes {second}')

and this will print:

First comes Amy, then comes Angela

Here is another example:

def smallest_word(words):
    """Return the smallest word along with its length"""
    smallest = None
    for word in words:
        if smallest is None or len(word) < len(smallest):
            smallest = word
    return smallest, len(smallest)

This function returns both the smallest word and the length of that word.

We can call it like this:

word, size = smallest_word(['apple', 'iron', 'cat', 'pigeon'])
print(f'The smallest word is {word} (of length {size})')

and this will print:

The smallest word is cat (of length 3)

Notice how unpacking is particularly helpful when a function returns multiple values!

Tuples vs lists

It’s important to recognize that lists and tuples fill different roles.

listtuple
Can add or remove itemsImmutable
Size dynamically determined as the program runsSize fixed once it is created
Typically stores items of the same typeOften stores items of different types
The items are usually independent of each otherThe items usually go together as a unit of information
Typically processed with iterationTypically processed by unpacking

You typically want to use a list when you are working with a list of things that are all the same type and you don’t know how many items you will have until you run the program

You typically want to use a tuple when you are returning several values from a function or if you know in advance exactly how many items how will have (and this never changes)