Part 5

Tuple

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

The following bit of code creates a tuple containing the coordinates of a point:

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 are ideal for when there is a set collection 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.

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

This means we can also easily return multiple values using tuples. Let's have alook at he 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

This function returns two values in a tuple. The return value is assigned to two variables at once:

min_value, max_value = minmax(my_list)

Using parentheses may make the notation more clear. On the left hand side of the assignment statement we also have a tuple, which contains two variable names. The values contained within the tuple returned by the function are assigned to these two variables.

(min_value, max_value) = minmax(my_list)

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
Loading

Please respond to a quick questionnaire on this week's materials.

Loading...
:
Loading...

Log in to view the quiz

You have reached the end of this section!

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