Tuple in Python
Keywords: tuple, array, list, immutable
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.
What is a tuple in Python
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.
Unlike the array, it is not possible to change values in a Tuple
How to create a Tuple in Python?
Similar to the Array, you create a Tuple by the following steps
- First you give the tuple a name
- Then assigns all values within a parenthesis (), where each value is separated by a comma “,”.
- Note that a tuple is created with parentheses, unlike the array that is created with brackets [].
Syntax: Tuple in Python
So if we use the steps above
tupleName = (value1, value2, value3, and so on.. )
Example: How to create a Tuple in Python
Let’s take a simple example on how to create a Tuple
animal_tuple = ("Cat", "Dog", "Fish", "Horse")
print(animal_tuple)
print(type(animal_tuple))
print(animal_tuple[0])
print(type(animal_tuple[1]))
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
print(animal_tuple[1])
We will get
Dog
Tuples in Python are immutable
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[1] = "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