The short definition
A tuple is an ordered, finite sequence of values. “Ordered” means position matters: (1, 2) and (2, 1) are different tuples. “Finite” means the tuple has a set number of elements, and that number does not change once the tuple is created.
Tuples in mathematics
In mathematics, a pair such as (a, b) is a 2-tuple, and a triple such as (a, b, c) is a 3-tuple. In general, an n-tuple is an ordered sequence of n elements. Coordinates such as (3, 4) are a familiar example, and order matters there: (3, 4) and (4, 3) name different points.
A set works differently. The set {1, 2} is the same as {2, 1}, while the tuples (1, 2) and (2, 1) are not.
Tuples in programming
Programming languages use the same idea. In Python, a tuple is written with parentheses or commas:
point = (3, 4)
x, y = point
print(x, y) # 3 4
In C++, the closest match is std::tuple:
#include <iostream>
#include <tuple>
int main() {
std::tuple<int, int> point{3, 4};
std::cout << std::get<0>(point) << ' ' << std::get<1>(point) << '\n';
}
The program prints 3 4.
Key properties
- Ordered: the position of each value matters.
- Fixed length: the number of values is set when the tuple is created.
- Mixed types: in Python and in
std::tuple, values can have different types, as in("Ada", 36). - Nestable: a tuple can hold other tuples, as in
((1, 2), (3, 4)).
Where to go next
To see how tuples differ from lists, read “What is a tuple and list?” For the full C++ treatment, see “Tuples in C++ With std::tuple”.