Tuples#
A tuple
is similar to a list
and can be used as an ordered collection of other objects.
A tuple
is defined much in the same way as a list
, but with parentheses instead of square brackets.
noble_gases = ('helium', 'neon', 'argon', 'krypton', 'xenon', 'radon')
Above is a tuple of noble gases, where the tuple is defined using round brackets.
type(noble_gases)
tuple
As with lists, we can use the index notation to identify particular elements in the tuple.
print(noble_gases[0])
helium
print(noble_gases[-1])
radon
The main difference between a tuple
and a list
is that lists
are mutable: they can be changed after they have been created, either by changing individual elements or deleting or adding elements to change the size of the list
. A tuple
, in contrast, is immutable: once it has been created it cannot be altered.
noble_gases[0] = 'Helium'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[5], line 1
----> 1 noble_gases[0] = 'Helium'
TypeError: 'tuple' object does not support item assignment
It is still possible to concatenate tuples, like lists, but the item that is being concatentated must be a tuple, hence the brackets and trailing comma.
noble_gases + ('oganesson',)
('helium', 'neon', 'argon', 'krypton', 'xenon', 'radon', 'oganesson')
The immutability of a tuple does not mean that the whole variable cannot be reassigned.
noble_gases = 'inert'
print(noble_gases)
inert
Additionally, like lists, tuple items can also consist of data of different types.
my_tuple = (0, 'a', 2.3)
print(my_tuple)
(0, 'a', 2.3)
You might be thinking, why have a less capable version of a lists
, when you could just use lists
everywhere and never have to worry about which is which? Tuples are computationally more efficient than lists: they use less memory and can be operated on faster, and are often used as the return type from functions that return more than one value. For complex code, there is also a benefit to limiting the number of possible bugs. And, if you do have a bug, you would ideally like the Python interpreter to tell you, rather than have your code run and do something unexpected; for example, your data analysis appears to run fine, but because you have a bug the number you end up quoting in the subsequent research article is incorrect! In general, unless you know that you are going to want to do something with your data that you can only do with a list
, it can be a good idea to use a tuple
instead.
If you do a collection of objects stored as a tuple
and you want to convert this to a list
you can use
list(my_tuple)
[0, 'a', 2.3]