Tuple in Python is a collection of objects in a specific order that cannot be changed after the tuple is declared. Therefore, a tuple is immutable.
A tuple is very similar to an Array. However, unlike the array, it is not possible to change values in a created tuple. This means that once you have created a tuple, the values in the tuple will remain the same until the tuple is removed.
Similar to the Array, you create a Tuple by the following syntax
tupleName = (value1, value2, value3, and so on.. )
Let’s take a quite simple example on how to create a Tuple
animal_tuple = ("Cat", "Dog", "Fish", "Horse") print(animal_tuple) print(type(animal_tuple)) print(animal_tuple) print(type(animal_tuple))
The result then becomes
('Cat', 'Dog', 'Fish', 'Horse') <class 'tuple'> Cat <class 'str'>
Note, similar to the Array, the index starts at zero. So if we for example write
We will get
You cannot change the values in a tuple.
Let’s take a short example, say for instance that we want to change our element “Dog” to “Snake”. By using the same method that we used for Array will cause a compilation error. Let’s have a look at the code,
animal_tuple = ("Cat", "Dog", "Fish", "Horse") animal_tuple = "Snake"
Will result in
TypeError: 'tuple' object does not support item assignment
Instead, you must remove the Tuple completely. It can be done through the reserved word del () (delete). You can then re-create the tuple:
So in our case, if we want to change Dog to Snake (element 1 in the animal_tuple), we have to write:
del(animal_tuple) animal_tuple = ("Cat", "Snake", "Fish", "Horse")
Therefore, be careful which data type you choose to store values in. If you know that there is a probability that the values will change, Arrays are definitely preferred.
For more information about Tuple in Python we recommend the Python Docs website