Tuples

The second data structure that we will discuss is the tuple. A tuple is very similar to a list, but is denoted by braces (normal brackets)

a_tuple = (1, 2, 3, 4, 5)
print(a_tuple)
(1, 2, 3, 4, 5)

Tuples have the type tuple

type(tuple)
tuple

We can index and slice tuples just like lists

colours = ('Duck Egg Blue', 'Oxblood Red', 'Forest Green', 'Royal Purple')

print(f'The third element of the colours tuple is: {colours[2]}')
print(f'The middle two elements of the colours tuple are: {colours[1:3]}')
The third element of the colours tuple is: Forest Green
The middle two elements of the colours tuple are: ('Oxblood Red', 'Forest Green')
Tip

There is one major difference between a tuple and a list - tuples are immutable - once they have been created they cannot be modified - Python will give an error if you try.

TipTest yourself

Change the third element of the following tuple to Lime Green

colours = ('Duck Egg Blue', 'Oxblood Red', 'Forest Green', 'Royal Purple')

and think about what the error is telling you.

We can combine two (or more) tuples to create a new tuple, for example

tuple_1 = ('Physical', 'Computational')
tuple_2 = ('Organic', 'Inorganic')

tuple_3 = tuple_1 + tuple_2
print(tuple_3)
('Physical', 'Computational', 'Organic', 'Inorganic')

You might wonder why this is useful. Well, put simply, tuples are less susceptible to erroneous modification. Since tuples are immutable, this means that any attempt to modify them will result in Python giving an error.

Tip

When thinking of which data structure to use:

  • Use a list when you need to modify its contents.
  • Use a tuple when you don’t need to modify its contents.