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.