Show the practical differences between a Python list and a tuple: mutability, available methods and hashability.
A list and a tuple that hold the same values compare as equal, but they are different types with different abilities.
values = [1, 2, 3]
frozen = (1, 2, 3)
print(values == frozen) # True - the same values
print(type(values).__name__, type(frozen).__name__) # list tuple
values.append(4)
print(values) # [1, 2, 3, 4]
try:
frozen.append(4)
except AttributeError as error:
print('AttributeError:', error)
# A tuple can be a dictionary key, a list cannot.
try:
{values: 'list key'}
except TypeError as error:
print('TypeError:', error)
The AttributeError confirms that a tuple has no append() method, because the methods that change a collection simply do not exist on it. The dictionary example shows the second difference. A tuple of hashable values can be used as a dictionary key, while a list cannot, because a list can change and its hash would change with it.
A tuple does have a few methods, they are just not the ones that change it. count() and index() work on a tuple, and it supports slicing, concatenation, and repetition, all of which give you a new tuple. A tuple is also slightly smaller and slightly faster to create than a list of the same length, because the list keeps some spare room for later additions.
The hashability point deserves one caveat. A tuple is only hashable when everything inside it is hashable too, so a tuple that contains a list raises a TypeError when you try to hash it. That is worth checking when you use a tuple as a dictionary key.