Python Tuples
Python · Tuples
Theory
A tuple is an ordered, immutable sequence, usually written with parentheses: coordinates = (28.6, 77.2). Like a list it supports indexing, slicing, len(), in and loops, but once created you cannot add, remove or replace items; coordinates[0] = 0 raises TypeError. It is actually the comma that makes a tuple, not the parentheses: (5) is just the int 5, while (5,) or 5, is a one-item tuple.
Immutability has practical benefits. A tuple of immutable values is hashable, so it can be a dictionary key or a set member, e.g. {(28.6, 77.2): 'Delhi'}, which a list can never be. Tuples are slightly smaller and faster to create than lists and signal 'this record will not change'. Note that immutability is shallow: a tuple holding a list cannot swap that list for another object, but the list inside can still be modified, and such a tuple is no longer hashable. Unpacking assigns the items to names in one go: lat, lon = coordinates.
Why we use it
Some data is a fixed record: a latitude/longitude pair, an RGB colour, a (name, salary) row. A tuple stores it safely so nothing changes it by accident, and it can be used as a dictionary key.
When to use it
Use a tuple for fixed-size records, function return values with several parts, and dict keys made of several values. Use a list when the collection will grow, shrink or be edited. For records with named fields, consider collections.namedtuple or a dataclass.
How it works
- coordinates = (28.6, 77.2) creates a tuple
- Python stores two references in a fixed-size block
- Trying to change an item, e.g. t[0] = 0? Yes: TypeError: no item assignment. No: Reading works like a list.
- Unpack with lat, lon = coordinates
- print(coordinates) shows (28.6, 77.2)
Syntax
my_tuple = (item1, item2, item3)Example
coordinates = (28.6, 77.2)Key points
- Immutable: items cannot be added, removed or replaced
- The comma makes the tuple: (5,) is a tuple, (5) is an int
- Hashable tuples can be dict keys and set members
- Slightly lighter than lists, and signal data that should not change
- Immutability is shallow: a list inside a tuple can still change
- Unpack in one line: lat, lon = coordinates