Tuples

The immutable cousin of the list is a tuple, a tuple acts in many ways the same as a tuple (such as indexing). However, the elements of a tuple cannot change once the object is defined. Let’s look at how a tuple is defined.

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

Like 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

Above it was mentioned that a tuple is an immutable type, that once created it’s objects cannot be altered. We can see this in action if we try and change the value of one of the elements in the tuple.

noble_gases[0] = 'Helium'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_2184/3354172952.py in <module>
----> 1 noble_gases[0] = 'Helium'

TypeError: 'tuple' object does not support item assignment

However, 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 overwritten.

noble_gases = 'inert'
print(noble_gases)
inert

Additionally, like lists, tuple items can also consist of data of different types.