Tuples and Named Tuples

Learn about the tuples and learn how to implement them.

Overview

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 we need to modify a tuple, we’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.

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 tuple into a function (or method on another object) that performs the action.

Tuples overlap with the idea of coordinates or dimensions. A mathematical (x, y) pair or (r, g, b) color are examples of tuples; the order matters a lot: the color (255, 0, 0) looks nothing like (0, 255, 0). The primary purpose of a tuple is to aggregate different pieces of data together into one container.

Creating tuples

We create a tuple by separating values with a comma. Usually, tuples are wrapped in parentheses to make them easy to read and to separate them from other parts of an expression, but this is not always mandatory. The following two assignments are identical (they record a stock, the current price, the 52-week high, and the 52-week low, for a rather profitable company):

Get hands-on with 1400+ tech skills courses.