A tuple is a built-in Python collection that is ordered and unchangeable. Python tuples are written with round brackets. Since tuples are immutable, iterating through a tuple is faster than a list. So there is a slight performance boost.
How to Create a Tuple in Python
To create a tuple in Python, “place all the elements inside the parentheses (), separated by a comma”. The parentheses are optional but are good practice to write them. A tuple can have any number of items, and they may be of different types.
Example 1
deserts = ('oreo', 1, True, ['Android', 'iOS'], 'pie')
print(deserts)
In the above example, we have taken a string, integer, and list datatype to create a tuple, and it is a valid tuple.
Example 2
Let us write a tuple without parentheses.
deserts = 'oreo', 1, True, ['Android', 'iOS'], 'pie'
print(deserts)
The above code is also valid, but it is not the best practice to write. That is why we add the parentheses around the items.
How to access tuple elements in Python
To access tuple elements in Python, refer to the index number inside square brackets.
Example
deserts = ('oreo', 1, True, ['Android', 'iOS'], 'pie')
print(deserts[3])
Output
How to loop through a Tuple in Python
To loop through a tuple in Python, you can use the “for loop”. A for loop is used for iterating over a sequence. The for loop does not require an indexing variable to be set beforehand.
Example
deserts = ('oreo', 'nougat', 'jellybean', 'pie')
for item in deserts:
print(item)
Output
Modifying tuple values
Let’s try to change the values in a tuple and see the result.
deserts = ('oreo', 'nougat', 'jellybean', 'pie')
deserts[1] = 'kitkat'
print(deserts)
I am using Visual Studio Code and have installed a Python extension called pylint. That is why my editor throws me an error saying that ‘deserts’ does not support item assignments. Unfortunately, that means we can not modify it. But still, let us run the file and see the output in the console.
Python tuple length
To find a length of a tuple in Python, you can use the “len()” function. The len() method returns how many elements a tuple has.
deserts = ('oreo', 'nougat', 'jellybean', 'pie')
print(len(deserts))
How to remove an element in Tuple
A tuple is unchangeable, so we can’t remove single or multiple elements but can delete the entire tuple.
deserts = ('oreo', 'nougat', 'jellybean', 'pie')
del deserts
print(deserts)
We have used the del keyword to delete the entire tuple. So the above code’s output will get an error because the tuple is already removed. So there is nothing to print because the compiler does not find any deserts tuple. So it throws an error.
That’s it.