Python Tuple
A Python tuple is an immutable sequence, usually written in parentheses: ("Alice", 20, "Guard"). Like a list it is ordered, indexed from 0, sliceable, and able to hold mixed types; unlike a list it cannot be changed after creation, so assigning to a position raises TypeError. Adding a field means building a new tuple rather than editing the existing one. Its item references are fixed, but a list inside it can still be mutated. For example, record = ("A", [1]) permits record[1].append(2).
Commas form nonempty tuples; the empty tuple is (). (1,) is a one-item tuple, while (1) is just the integer, and 1, 2 without parentheses is already a tuple. tuple(["a", "b"]) converts any iterable into a tuple. Parentheses are still required where a bare comma would be ambiguous, such as inside a function call.
Unpacking assigns the fields to names in one statement: name, age, position = player. Without a starred target, the number of names must match the number of items, or Python raises ValueError reporting too many or not enough values. Unpacking also works in a for loop over a list of tuples, which is how tabular rows are usually read, and it is what makes a function appear to return several values: the values arrive as one tuple.
Use a tuple when the positions mean fixed fields of one record, and a list when the collection grows, shrinks, or is reordered. Immutability carries a practical benefit: a tuple whose items are all hashable is itself hashable, so it can serve as a dictionary key or a set element, which a list cannot. It also signals intent, telling a later reader that this record is not meant to be edited in place.
References: Python tuples, Tuples and sequences. See it in use in Python Collections and Comprehensions.
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
