Programming Search⌘K

Conceptintro

Tuple

Also called tuple, tuple type, n-tuple, pair, triple, ordered pair, value tuple.

A tuple groups a fixed number of values by position. Each position can have its own type. Programs read the parts by index or unpack them into variables.

Applies to
core-languages

Idea

A tuple is a group of values by position. The pair (2, 9) has two parts: the first is 2, the second is 9. The Rust book says that a tuple "is a general way of grouping together a number of values with a variety of types into one compound type".1 The number of parts is part of the type: "Tuples have a fixed length: Once declared, they cannot grow or shrink in size."1

def min_max(values: list[int]) -> tuple[int, int]:
    return min(values), max(values)


pair = min_max([7, 2, 9, 4])
print(pair)

lo, hi = pair
print("lo:", lo, "hi:", hi)
print("second part:", pair[1])
Output
(2, 9)
lo: 2 hi: 9
second part: 9

A tuple is the simplest product type (see Product type). It has no names, only positions. That makes it short to write, and a good fit for a small result such as a minimum and a maximum. For data with many parts, or data that lives long, a record with named fields is clearer (see Record type).

How it works

Build. Most languages write a tuple as values in parentheses with commas between them, as in (2, 9). Python needs only the commas: "A tuple consists of a number of values separated by commas".2 TypeScript and JavaScript use an array literal, as in [2, 9].

Read by position. Each part has an index, which starts at 0 in most languages. The syntax differs: t[1] in Python, t.1 in Rust, t.Item2 in C#, std::get<1>(t) in C++.

Unpack. A program can bind each part to its own variable in one statement. Python calls this "sequence unpacking", and it "requires that there are as many variables on the left side of the equals sign as there are elements in the sequence".2 JavaScript has destructuring, a syntax that "makes it possible to unpack values from arrays, or properties from objects, into distinct variables".3 C++ has structured bindings, which bind names "to subobjects or elements of the initializer".4 In Rust and the ML family, a tuple pattern in a let or a match does the same.

Type. The type of a tuple lists the type of each position, as in (i32, f64) in Rust, tuple[int, str] in Python or [string, number] in TypeScript. TypeScript describes a tuple type as an array type "that knows exactly how many elements it contains, and exactly which types it contains at specific positions".5 Two tuple types with the same parts in a different order are different types.

Equality. Two tuples are equal when they have the same number of parts and the parts at each position are equal. C# says that == and != "compare members of the left-hand operand with the corresponding members of the right-hand operand following the order of tuple elements".6

The empty tuple. A tuple with no parts has only one value. Rust calls it unit: "This value and its corresponding type are both written () and represent an empty value or an empty return type."1

Named tuples. Some languages let a tuple also have names for its positions. Python's namedtuple makes "tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable".7 C# lets a program name the elements, as in (Sum: 4.5, Count: 3).6 A named tuple is close to a record, but it can still be read by position.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaIdiom
CIdiom
C#Native
JavaScriptIdiom
TypeScriptNative
GoIdiom
RustNative
KotlinNativeThe standard library has the Pair and Triple data classes, and a destructuring declaration unpacks them; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLNativeA row value such as (1, 'a') is a tuple, and rows can be compared as tuples.
BashIdiomBash has no tuple type, but a function can print several words that the caller reads into separate variables.
PowerShellIdiomAn array holds values by position, and the .NET System.Tuple and System.ValueTuple types are available; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup has no types.
CSSDoes not applyStyle rules have no types.
Regular expressionsDoes not applyA pattern has no types.

The example files return a minimum and a maximum as a pair, unpack the pair and compare two pairs.

Language Verdict Form
Python native tuple, immutable; namedtuple and typing.NamedTuple for names278
JavaScript idiom an array of fixed length, unpacked with destructuring3
TypeScript native a tuple type such as [number, number]5
Java idiom a small record, or Map.entry for a pair
C idiom a struct with one member for each position
C++ native std::pair and std::tuple, with structured bindings94
C# native value tuples such as (int, int)6
Go idiom multiple return values, or a small struct10
Rust native tuple types such as (i32, i32)1
Kotlin native Pair and Triple11
PowerShell idiom an array, or [System.Tuple] from .NET
Bash idiom separate variables, or a function that prints several words
SQL native a row value such as (1, 'a')
Regex n/a a pattern has no types
HTML/CSS n/a markup has no types

Python. Tuples "are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking".2 typing.NamedTuple is the "Typed version of collections.namedtuple()".8

C++. In the standard, "tuples are heterogeneous, fixed-size collections of values".9 A std::pair is a tuple with two elements.

C#. A tuple such as (double, int) is a value type, and "tuple elements are public fields. That design makes tuples mutable value types."6

Java. Java has no tuple type. JEP 395 says that "Records can be thought of as nominal tuples".12 So a Java program declares a small record, such as record MinMax(int min, int max), in place of a pair.

Go. Go has no tuple type, but "functions and methods can return multiple values".10 The results must be assigned to separate variables at the call. A program that must store the parts together uses a struct.

Kotlin. "The standard library provides the Pair and Triple classes." The same page says that named data classes are usually the better design.11

PythonGitHub
from typing import NamedTuple


class MinMax(NamedTuple):
    lo: int
    hi: int


def min_max(values: list[int]) -> tuple[int, int]:
    return min(values), max(values)


def yn(b: bool) -> str:
    return "yes" if b else "no"


pair = min_max([7, 2, 9, 4])
print("pair:", pair)
lo, hi = pair
print("lo:", lo, "hi:", hi)
print("second part:", pair[1])
print("equal pairs:", yn(pair == (2, 9)))

named = MinMax(lo, hi)
print("named:", named, "hi =", named.hi, "equal to plain:", yn(named == pair))
Output
pair: (2, 9)
lo: 2 hi: 9
second part: 9
equal pairs: yes
named: MinMax(lo=2, hi=9) hi = 9 equal to plain: yes
  • Verdict: native. A tuple is immutable, and return a, b builds one without parentheses.
  • lo, hi = pair unpacks the parts. The number of names must match the number of parts.
  • A NamedTuple adds names, but it is still a tuple, so it equals a plain tuple with the same parts.
#include <algorithm>
#include <iostream>
#include <string>
#include <tuple>
#include <utility>
#include <vector>

std::pair<int, int> min_max(const std::vector<int>& values) {
    auto [lo, hi] = std::minmax_element(values.begin(), values.end());
    return {*lo, *hi};
}

int main() {
    auto pair = min_max({7, 2, 9, 4});
    std::cout << "pair: (" << pair.first << ", " << pair.second << ")\n";
    auto [lo, hi] = pair;
    std::cout << "lo: " << lo << " hi: " << hi << "\n";
    std::cout << "second part: " << std::get<1>(pair) << "\n";
    std::cout << "equal pairs: " << (pair == std::pair{2, 9} ? "yes" : "no") << "\n";

    std::tuple<std::string, int, bool> t{"Ada", 36, true};
    std::cout << "tuple size: " << std::tuple_size_v<decltype(t)> << " first: " << std::get<0>(t) << "\n";
}
Output
pair: (2, 9)
lo: 2 hi: 9
second part: 9
equal pairs: yes
tuple size: 3 first: Ada
  • Verdict: native. std::pair holds two values, and std::tuple holds any fixed number of values.
  • auto [lo, hi] = pair is a structured binding (C++17). std::get<1> reads a part by position.
  • == compares the parts in order.
JavaGitHub
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class Main {
    record Pair<A, B>(A first, B second) {}

    static Pair<Integer, Integer> minMax(List<Integer> values) {
        return new Pair<>(Collections.min(values), Collections.max(values));
    }

    static String yn(boolean b) {
        return b ? "yes" : "no";
    }

    public static void main(String[] args) {
        Pair<Integer, Integer> pair = minMax(List.of(7, 2, 9, 4));
        System.out.println("pair: " + pair);
        if (pair instanceof Pair<Integer, Integer>(Integer lo, Integer hi)) {
            System.out.println("lo: " + lo + " hi: " + hi);
        }
        System.out.println("second part: " + pair.second());
        System.out.println("equal pairs: " + yn(pair.equals(new Pair<>(2, 9))));

        Map.Entry<String, Integer> entry = Map.entry("Ada", 36);
        System.out.println("entry: " + entry.getKey() + " " + entry.getValue());
    }
}
Output
pair: Pair[first=2, second=9]
lo: 2 hi: 9
second part: 9
equal pairs: yes
entry: Ada 36
  • Verdict: idiom. Java has no tuple type, so the program declares a small generic record.
  • A record pattern such as Pair<Integer, Integer>(Integer lo, Integer hi) unpacks the parts.
  • Map.entry makes an immutable pair of a key and a value.
#include <stdio.h>

struct min_max {
    int lo;
    int hi;
};

static struct min_max find_min_max(const int *values, int n) {
    struct min_max r = {values[0], values[0]};
    for (int i = 1; i < n; i++) {
        if (values[i] < r.lo) {
            r.lo = values[i];
        }
        if (values[i] > r.hi) {
            r.hi = values[i];
        }
    }
    return r;
}

int main(void) {
    int values[] = {7, 2, 9, 4};
    struct min_max pair = find_min_max(values, 4);
    printf("pair: (%d, %d)\n", pair.lo, pair.hi);

    int lo = pair.lo, hi = pair.hi;
    printf("lo: %d hi: %d\n", lo, hi);
    printf("second part: %d\n", pair.hi);

    struct min_max other = {2, 9};
    int equal = pair.lo == other.lo && pair.hi == other.hi;
    printf("equal pairs: %s\n", equal ? "yes" : "no");
    return 0;
}
Output
pair: (2, 9)
lo: 2 hi: 9
second part: 9
equal pairs: yes
  • Verdict: idiom. C has no tuple type. A small struct returns several values from a function.
  • The initializer {values[0], values[0]} fills the members by position.
  • C has no == for structs, so the program compares the members.
var pair = MinMax(new[] { 7, 2, 9, 4 });
Console.WriteLine($"pair: {pair}");
var (lo, hi) = pair;
Console.WriteLine($"lo: {lo} hi: {hi}");
Console.WriteLine($"second part: {pair.Item2}");
Console.WriteLine("equal pairs: " + Yn(pair == (2, 9)));
Console.WriteLine($"by name: hi = {pair.Hi}");

static (int Lo, int Hi) MinMax(int[] values) => (values.Min(), values.Max());

static string Yn(bool b) => b ? "yes" : "no";
Output
pair: (2, 9)
lo: 2 hi: 9
second part: 9
equal pairs: yes
by name: hi = 9
  • Verdict: native. A value tuple such as (int Lo, int Hi) is a value type with public fields.
  • The names Lo and Hi are extra names for Item1 and Item2.
  • == compares the elements in order and ignores the names.
JavaScriptGitHub
const yn = (b) => (b ? "yes" : "no");

function minMax(values) {
  return [Math.min(...values), Math.max(...values)];
}

const pair = minMax([7, 2, 9, 4]);
console.log("pair:", JSON.stringify(pair));
const [lo, hi] = pair;
console.log("lo:", lo, "hi:", hi);
console.log("second part:", pair[1]);

const other = [2, 9];
const samePair = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
console.log("equal pairs:", yn(samePair(pair, other)));
console.log("equal pairs, ===:", yn(pair === other));
Output
pair: [2,9]
lo: 2 hi: 9
second part: 9
equal pairs: yes
equal pairs, ===: no
  • Verdict: idiom. JavaScript has no tuple type. A short array plays the role, and destructuring unpacks it.
  • Nothing fixes the length or the types of the parts.
  • === compares identity, so two arrays with the same parts are not ===.
TypeScriptGitHub
const yn = (b: boolean): string => (b ? "yes" : "no");

function minMax(values: number[]): [lo: number, hi: number] {
  return [Math.min(...values), Math.max(...values)];
}

const pair = minMax([7, 2, 9, 4]);
console.log("pair: " + JSON.stringify(pair));
const [lo, hi] = pair;
console.log(`lo: ${lo} hi: ${hi}`);
console.log(`second part: ${pair[1]}`);

const other: [number, number] = [2, 9];
const samePair = (a: readonly number[], b: readonly number[]): boolean =>
  a.length === b.length && a.every((x, i) => x === b[i]);
console.log("equal pairs: " + yn(samePair(pair, other)));
console.log(`length in the type: ${pair.length}`);
Output
pair: [2,9]
lo: 2 hi: 9
second part: 9
equal pairs: yes
length in the type: 2
  • Verdict: native. A tuple type such as [lo: number, hi: number] fixes the number of parts and the type of each one.
  • The type checker knows that pair.length is 2 and refuses pair[2].
  • At run time a tuple is a plain array.
package main

import (
	"fmt"
	"slices"
)

type pair struct {
	lo, hi int
}

func minMax(values []int) (int, int) {
	return slices.Min(values), slices.Max(values)
}

func yn(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

func main() {
	lo, hi := minMax([]int{7, 2, 9, 4})
	fmt.Println("lo:", lo, "hi:", hi)

	p := pair{lo, hi}
	fmt.Println("pair:", p)
	fmt.Println("second part:", p.hi)
	fmt.Println("equal pairs:", yn(p == pair{2, 9}))
}
Output
lo: 2 hi: 9
pair: {2 9}
second part: 9
equal pairs: yes
  • Verdict: idiom. Go has no tuple type. A function returns several values, and the caller assigns them to separate variables.
  • To keep the parts together, the program declares a small struct.
  • Structs with comparable fields can be compared with ==.
RustGitHub
fn min_max(values: &[i32]) -> (i32, i32) {
    let lo = *values.iter().min().unwrap();
    let hi = *values.iter().max().unwrap();
    (lo, hi)
}

fn yn(b: bool) -> &'static str {
    if b { "yes" } else { "no" }
}

fn main() {
    let pair = min_max(&[7, 2, 9, 4]);
    println!("pair: {:?}", pair);
    let (lo, hi) = pair;
    println!("lo: {} hi: {}", lo, hi);
    println!("second part: {}", pair.1);
    println!("equal pairs: {}", yn(pair == (2, 9)));
    println!("unit: {:?}", ());
}
Output
pair: (2, 9)
lo: 2 hi: 9
second part: 9
equal pairs: yes
unit: ()
  • Verdict: native. A tuple type such as (i32, i32) lists the type of each position.
  • pair.1 reads a part by position, and let (lo, hi) = pair unpacks it with a pattern.
  • The empty tuple () is the unit value.
  • Records. A product whose parts have names. Wikipedia describes records as an alternative to tuples, "featuring unordered elements accessed by label".13 See Record type.
  • Unit. The empty tuple, the type with one value. See Product type.
  • Variadic tuples. C++ std::tuple and TypeScript tuple types can have any number of elements, and generic code can work on the whole list of types.
  • Relational tuples. Relational databases can call a row of a table a tuple.13
  • Arrays. An array has many elements of one type, and its length is often not part of its type. A tuple has a fixed number of parts, each with its own type.

Pitfalls

A one-part tuple needs a comma

In Python, parentheses alone do not make a tuple. The tutorial says that "a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses)".2 Here names is a string, so the loop runs over its characters.

This code runs but gives a wrong answer on purpose.

names = ("Ada")
for n in names:
    print(n)
Output
A
d
a

The fix is a trailing comma: names = ("Ada",).

Positions do not carry meaning

A tuple says nothing about what each position means. A pair (lat, lon) and a pair (lon, lat) have the same type, so a call that swaps them compiles and gives wrong results. In C#, element names do not help with equality: "the == and != operations don't take tuple field names into account".6 So (A: 5, B: 10) == (B: 5, A: 10) is true. When the meaning of each part matters, use a record with named fields.

A Python tuple can hold mutable parts

A tuple is immutable, but its parts can be mutable. The tutorial shows a tuple of two lists: tuples "can contain mutable objects".2 A change inside one of the lists changes what the tuple shows. Such a tuple also cannot be a dictionary key: "if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key".2

Cost

A tuple stores each part once. In C++, C#, Go, Rust and C, a tuple or a small struct is a value with no header, so it can live in registers or on the stack. A C# value tuple is copied on assignment. In Python and JavaScript, a tuple or an array is an object on the heap that holds references to its parts. Unpacking a tuple costs one read for each part.

History

The word comes from mathematics. Wikipedia says that it "originated as an abstraction of the sequence: single, couple/double, triple, quadruple, quintuple, sextuple".13 In programming, "Most typed functional programming languages implement tuples directly as product types".13 Many later languages added tuples to the standard library or to the core language, such as std::tuple in C++ and value tuples in C#.96

References

  1. The Rust Programming Language, 3.2 Data Types, The Tuple Type
  2. The Python Tutorial, 5. Data Structures, 5.3 Tuples and Sequences; 5.5 Dictionaries
  3. MDN Web Docs, Destructuring, the introduction
  4. cppreference.com, Structured binding declaration, the introduction
  5. TypeScript Handbook, Object Types, Tuple Types
  6. C# language reference, Tuple types, the introduction; Tuple field names; Tuple equality
  7. The Python Standard Library, collections, namedtuple(), namedtuple() Factory Function for Tuples with Named Fields
  8. The Python Standard Library, typing, NamedTuple, class typing.NamedTuple
  9. Working Draft, Standard for Programming Language C++ (N4950), [tuple.general], 22.4.1 In general
  10. Effective Go, Multiple return values
  11. Kotlin documentation, Data classes, Standard data classes
  12. JEP 395: Records, Records and sealed classes; Summary
  13. Tuple, Wikipedia, the introduction; Etymology

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/8RDPSX/text.yaml