A tuple is similar to the list: ordered, allows repetition of items.
There is just one difference: a tuple is immutable.
Initialization
Empty Tuple
people = ()
Tuple with initial values
people = ('Bob', 'Mary')
Adding in a Tuple
Tuples are immutable, if you try to add an item, you will see an error.
people = ('Bob', 'Mary')
people[2] = 'Sarah'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Updating in a Tuple
Update an item will also return an error.
But there is a trick, you can convert into a list, change the item and then convert it back to a tuple.
people = ('Bob', 'Mary')
people_list = list(people)
people_list[1] = 'Sarah'
people = tuple(people_list)
print(people)
('Bob', 'Sarah')
Deleting in a Tuple
For the same reason you can’t add an item, you also can’t delete an item, since they are immutable.
Retrieving in a Tuple
Use the index to reference the item.
people = ('Bob', 'Mary')
print(people[1])
Mary
Iterating over Tuples
people = ('Bob', 'Mary')
for person in people:
print(person)
Bob
Mary
Check if a given item already exists in a Tuple
people = ('Bob', 'Mary')
if 'Bob' in people:
print('Bob exists!')
else:
print('There is no Bob!')