Part 5

Tuple

The tuple is a data structure which is, in many ways, similar to a list. The most important differences between the two are:

  • Tuples are enclosed in parentheses (), while lists are enclosed in square brackets []
  • Tuples are immutable, while the contents of a list may change

Given that in terms of data modeling, tuples are nearly completely the same as lists, it might even be easier for a beginning programmer to not introduce them and just stick to using lists. However, as tuples often do appear in Python code you'll see elsewhere, it makes sense to dwelve on them at least enough so that you'll be familiar with their syntax.

The following bit of code creates a tuple containing the x,y -coordinates of a point in two-dimensional space:

point = (10, 20)

The items stored in a tuple are accessed by index, just like the items stored in a list:

point = (10, 20)
print("x coordinate:", point[0])
print("y coordinate:", point[1])
Sample output

x coordinate: 10 y coordinate: 20

The values stored in a tuple cannot be changed after the tuple has been defined. The following will not work:

point = (10, 20)
point[0] = 15
Sample output

TypeError: 'tuple' object does not support item assignment

Loading
Loading
Loading

What is the purpose of a tuple?

Tuples often appear when you need to store a fixed number of values which are in some way connected. For example, when there is a need to handle the x and y coordinates of a point, a tuple is a natural choice, because coordinates will always consist of two values:

point = (10, 20)

Technically it is of course possible to also use a list to store these:

point = [10, 20]

A list is a collection of consecutive items in a certain order. The size of a list may also change. When we are storing the coordinates of a point, we want to store the x and y coordinates specifically, not an arbitrary list containing those values.

In terms of functional differences, because tuples are immutable, unlike lists, they can be used as keys in a dictionary. The following bit of code creates a dictionary, where the keys are coordinate points:

points = {}
points[(3, 5)] = "monkey"
points[(5, 0)] = "banana"
points[(1, 2)] = "harpsichord"
print(points[(3, 5)])
Sample output
monkey

Attempting a similar dictionary definition using lists would not work:

points = {}
points[[3, 5]] = "monkey"
points[[5, 0]] = "banana"
points[[1, 2]] = "harpsichord"
print(points[[3, 5]])
Sample output

TypeError: unhashable type: 'list'

Tuples without parentheses

The parentheses are not strictly necessary when defining tuples. The following two variable assignments are identical in their results:

numbers = (1, 2, 3)
numbers = 1, 2, 3

Tuples as return values

While this can be a bit technical, tuples are also used to get around the restriction in the Python language that technically, functions can only return one value. Let's have a look at the following example:

def minmax(my_list):
  return min(my_list), max(my_list)

my_list = [33, 5, 21, 7, 88, 312, 5]

min_value, max_value = minmax(my_list)
print(f"The smallest item is {min_value} and the greatest item is {max_value}")
Sample output

The smallest item is 5 and the greatest item is 312

What this function actually returns is a tuple containing the two values, which then gets unpacked (through another Python language feature called tuple unpacking) back into two different variables at once using the assignment statement min_value, max_value = minmax(my_list). Thus, this assignment is equivalent to the following, which also works with the exact same minmax function:

tuple = minmax(my_list)
min_value = tuple[0]
max_value = tuple[1]

Using parentheses may make what's happening more clear:

def minmax(my_list):
  return (min(my_list), max(my_list))

my_list = [33, 5, 21, 7, 88, 312, 5]

(min_value, max_value) = minmax(my_list)
print(f"The smallest item is {min_value} and the greatest item is {max_value}")

You may remember the dictionary method items in the previous section. We used it to access all the keys and values stored in a dictionary:

my_dictionary = {}

my_dictionary["apina"] = "monkey"
my_dictionary["banaani"] = "banana"
my_dictionary["cembalo"] = "harpsichord"

for key, value in my_dictionary.items():
    print("key:", key)
    print("value:", value)

Tuples are at work here, too. The method my_dictionary.items() returns each key-value pair as a tuple, where the first item is the key and the second item is the value.

Another common use case for tuples is swapping the values of two variables:

number1, number2 = number2, number1

The assignment statement above swaps the values stored in the variables number1 and number2. The result is identical to what is achieved with the following bit of code, using a helper variable:

helper_var = number1
number1 = number2
number2 = helper_var
Loading
You have reached the end of this section! Continue to the next section:

You can check your current points from the blue blob in the bottom-right corner of the page.