Codectionary / Developer documentation / Python

Tuples

A tuple is an ordered, immutable collection, created with parentheses (or often just commas). Once created, a tuple's contents cannot be changed, added to, or removed - this immutability makes tuples faster than lists and safe to use as dictionary keys or in sets. Tuples are commonly used for fixed collections of related values, like coordinates or RGB colors, and for returning multiple values from a function.

Syntax

(item1, item2, item3)

Examples

Creating Tuples

Basic tuple creation and access, identical in syntax to lists except for the brackets used.

point = (3, 4)
colors = ("red", "green", "blue")

print(point[0])       # 3
print(colors[-1])     # blue

single = (5,)  # a comma is required for a one-item tuple
print(type(single))   # <class 'tuple'>

Tuple Unpacking

Assigning each tuple element to its own variable in one line.

point = (3, 4)
x, y = point
print(x, y)  # 3 4

def get_min_max(numbers):
    return min(numbers), max(numbers)

low, high = get_min_max([4, 1, 9, 2])
print(f"Min: {low}, Max: {high}")

Immutability

Attempting to modify a tuple raises an error - this is by design.

point = (3, 4)

try:
    point[0] = 10
except TypeError as e:
    print(f"Error: {e}")

# To "change" a tuple, create a new one instead
point = (10, point[1])
print(point)  # (10, 4)

Named Tuples

Using collections.namedtuple for tuples with readable, named fields.

from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)

print(p.x, p.y)   # 3 4
print(p[0], p[1]) # 3 4 (still works like a regular tuple)

Best practices

  • Use tuples for fixed collections that should never change, and lists when the contents need to grow or be reordered
  • Don't forget the trailing comma when creating a single-element tuple - (5) is just the number 5, not a tuple
  • Use tuple unpacking to return and receive multiple values from a function cleanly
  • Reach for namedtuple (or a dataclass) when a plain tuple starts feeling unclear about what each position means
  • Tuples can be used as dictionary keys because they are immutable and hashable - lists cannot

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading