Background on Tuples
With dictionaries* to handle unordered objects and lists to handle ordered objects, you might wonder where the data type tuple should be utilized. Python’s creator is a mathematician by training and he created the tuple as a simple association of objects. The word ‘tuple’ is derived from mathematics and refers to a finite ordered sequence of elements.
The core type tuple (an unnamed tuple) follow the same format as a list except that it cannot be changed in place (immutable) and is usually written as a series of items in parentheses. As a rule of thumb, use tuples to handle cases of fixed associations where none of the elements will change.
*Python 3.6+ do have ordered dictionaries but for backwards compatibility, we cannot assume this to be the case.
Defining Tuples
Tuples do not have all the methods that lists have. Notably any list method which deletes, modifies or appends an element will not be allowed. These excluded methods and assignments are ones that implement in-place algorithms. However, as a caveat, elements within a list can be changed by its internal methods though they cannot be directly reassigned. As an example, let us look at the difference between a tuple a
and a list b
.
# let us define a tuple a…