Tuples

What Is a Tuple in Python? With an Example Program

A tuple in Python is an ordered, immutable group of values. This example program creates, unpacks and indexes one, then shows the C++ version.

On this page
  1. What a tuple is in Python
  2. Example program
  3. Returning several values from a function
  4. The one-item trap
  5. The same record in C++

What a tuple is in Python

A tuple is an ordered collection of values that cannot be changed after it is created. You make one with parentheses and commas. Its items can have different types, and you read them by position, starting at 0.

Example program

This program makes a product record, unpacks it into separate variables, reads one item by index and checks how many items it has:

# A product record: name, price and color
item = ("coffee mug", 12.5, "blue")

name, price, color = item  # unpack the tuple into three variables
print(f"{name} costs {price:.2f} and is {color}.")

print("First item:", item[0])        # indexing starts at 0
print("Number of items:", len(item))

# item[1] = 15.0  # would raise TypeError: a tuple cannot be changed

The output is:

coffee mug costs 12.50 and is blue.
First item: coffee mug
Number of items: 3

The number of variables on the left of the unpacking must match the number of items. If it doesn’t, Python raises a ValueError.

Returning several values from a function

Tuples are a common way to return more than one value:

def min_and_max(values):
    return min(values), max(values)

low, high = min_and_max([4, 9, 1])
print(low, high)  # 1 9

The one-item trap

A single value in parentheses is just that value. (5) is an integer, and (5,) is a tuple. For a fuller look at the empty and one-item cases, see the question “Is tuple {} or ()?”

The same record in C++

C++ has no tuple literal syntax, so you build a std::tuple with values inside braces, then unpack it with a structured binding:

#include <iostream>
#include <string>
#include <tuple>

int main() {
    std::tuple<std::string, double, std::string> item{"coffee mug", 12.5, "blue"};

    auto [name, price, color] = item;
    std::cout << name << " costs " << price << " and is " << color << ".\n";
}

The program prints coffee mug costs 12.5 and is blue. The C++ version uses the default formatting for the price, so 12.5 appears without a trailing zero.

The complete guide to tuples

Tuples in C++ With std::tuple
Read the guide

Keep exploring

Guides from other topics

All topics →

The Latest C++ Standard

C++23 is the most recent C++ standard at the time of writing, with C++26 next. Here is what changed, how versions are named, and how to compile for each.

C++ Standards 3 min read