Tuples#
The second data structure that we will discuss is the tuple
. A tuple
is very similar to a list
:
a_tuple = (1, 2, 3, 4, 5)
print(a_tuple)
(1, 2, 3, 4, 5)
type(a_tuple)
tuple
As you can see above, the only difference in syntax is the type of brackets, we use square brackets to create a list
, whereas we use round brackets to create a 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')
At this point you might well be thinking, “Well what’s the point of a tuple if it’s just like a list?” The key difference is that tuples are immutable: once they have been created, they cannot be changed:
colours[2] = 'Lime Green'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[4], line 1
----> 1 colours[2] = 'Lime Green'
TypeError: 'tuple' object does not support item assignment
This does not mean that we cannot do anything with tuples at all, for example we can still concatenate two of them together just like lists:
tuple_1 = ('Physical', 'Computational')
tuple_2 = ('Organic', 'Inorganic')
tuple_1 + tuple_2
('Physical', 'Computational', 'Organic', 'Inorganic')
The main message is that we cannot modify the tuple itself. We can add two of them together, but we cannot change what is actually in a given tuple once it has been created.
Of course, this all begs the question: “Why would I ever use a tuple rather than a list?” There are several reasons, but perhaps the most important one is that tuples are much less error-prone. Precisely because tuples are immutable, it is literally impossible for your code to accidentally modify them in an undesirable way. Using lists, it is possible (and indeed it happens quite often) that you can unintentionally mutate the contents of the list in such a way as to end up with the wrong result. The advantage of tuples is therefore that, so long as you do not need to change its contents, it guarantees that no matter what the rest of your code does, it will not accidentally mutate a tuple. That being said, a lot of the time we do need to change the contents of our data structures, so then we use lists.
Tip
A good rule of thumb is the following: if you need to use a list, because you need it to be mutable, then go ahead. But if you do not need to change the contents, then always use a tuple instead.