Tuples
More precisely, we can define a sequence as a finite and ordered set of elements.
There are two types of sequences in Python: tuples and lists.
Tuples
In mathematics, we call tuples "ordered collections of objects". More precisely, we will call n-tuple or n-tuple a collection containing n objects. You will find more information on the page Tuple - Wikipedia.
The common term in programming is the corresponding anglicism, the tuple.
- tuple elements are placed between parentheses:
(val1, val2, val3)
- tuples are ordered, each element is associated with an index
- tuples are not modifiable
- tuple elements can be of different types: you can combine strings, integers, objects, in the same tuple.
Let's start with a simple example:
first_tuple = (1, 9, 42, 13, 24)
Thus, in the first_tuple
variable, we have:
- the value 1 at position 0
- the value 9 at position 1
- the value 42 at position 2
- the value 13 at position 3
- the value 24 at position 4
To access these values, we use bracket-based notation. The code below allows analyzing each element of the tuple. We notice that we can easily make different native types coexist within the same tuple.
my_tuple = (42, "cat", 12, True)
print(type(my_tuple), ":", my_tuple)
print(type(my_tuple[0]), ":", my_tuple[0])
print(type(my_tuple[1]), ":", my_tuple[1])
print(type(my_tuple[2]), ":", my_tuple[2])
print(type(my_tuple[3]), ":", my_tuple[3])
<class 'tuple'> : (42, 'cat', 12, True)
<class 'int'> : 42
<class 'str'> : cat
<class 'int'> : 12
<class 'bool'> : True
Let's take our addition()
function again. We can modify it so that instead of returning the sum of the two values, it returns a tuple containing value a, value b, and finally the sum of the two. Thus, we preserve all the information: we know the sum of the two values, but we can also find out how it was calculated.
def addition(int_a, int_b):
if type(int_a) == type(int_b) == type(1):
return (int_a, int_b, int_a + int_b)
else:
return "TYPE ERROR"
print(addition(12, 8))
(12, 8, 20)
my_tuple = (1, 2, 3)
# Trying to modify an element raises an error
my_tuple[1] = 4 # This generates an error