Tuples and named tuples
Tuples are objects that can store a specific number of other objects in sequence. They are immutable, meaning we can't add, remove, or replace objects on the fly. This may seem like a massive restriction, but the truth is, if you need to modify a tuple, you're using the wrong data type (usually, a
list would be more suitable). The primary benefit of tuples' immutability is a tuple of immutable objects (like strings and numbers and other tuples) has a hash value, allowing us to use them as keys in dictionaries, and members of a set. (A tuple that contains a mutable structure, like a list, set, or dict, isn't composed of immutable items, and doesn't have a hash value. We'll look closely at this distinction in the next section.)
Instances of Python's built-in generic
tuple class are used to store data; behavior cannot be associated with a built-in tuple. If we require behavior to manipulate a tuple, we have to pass the...