Python Tuples
Python Tuple is a collection of items.
The following is a simple tuple with three elements.
('apple', 'banana', 'cherry')
A tuple can have items of different datatypes.
In the following tuple, we have three items where the first is of type string, the second is a number, and the third is a boolean.
('apple', 25, True)
Items in a tuple are ordered. The index of items start from zero and increment in steps of one, from left to right. The first item has an index of 0, the second item has an index of 1, and the so on.
('apple', 'banana', 'cherry')
0 1 2 <--- indices
Since items in tuple are ordered, we can access individual items using index.
In the following program, we take tuple of strings, access the items using index, and print them to output.
example.py
names = ('apple', 'banana', 'cherry')
print(names[0])
print(names[1])
print(names[2])
Output
apple
banana
cherry
Tuple is an iterable object. So, we could iterate over the items of a tuple using for loop.
example.py
names = ('apple', 'banana', 'cherry')
for item in names:
print(item)
Output
apple
banana
cherry
Tuple is immutable. We can neither append items, delete items nor assign new values for existing items.
When we try to update an item in a tuple, we get TypeError, as shown in the following program’s output.
example.py
names = ('apple', 'banana', 'cherry')
names[1] = 'mango'
Output
Traceback (most recent call last):
File "example.py", line 2, in <module>
names[1] = 'mango'
TypeError: 'tuple' object does not support item assignment
Tuple Programs
Refer the tutorial Python Tuple Programs that cover different use-cases with Tuples.
Conclusion
In this Python Tutorial, we learned about Python Tuples.