Tuple Basics

Difficulty: Intermediate

Tuples are ordered, immutable sequences in Python, defined by enclosing comma-separated values in parentheses (). They look similar to lists but have a fundamentally different purpose: while lists represent a collection of items that may change, tuples represent a fixed collection of related values, like coordinates (x, y), a database row, or an RGB color value. The immutability of tuples makes them suitable as dictionary keys, set elements, and function return values.

Creating tuples has a subtle gotcha: it is the comma that makes a tuple, not the parentheses. A single-element tuple requires a trailing comma: (42,) is a tuple, but (42) is just the integer 42 wrapped in grouping parentheses. An empty tuple is created with () or tuple(). You can also create tuples from other iterables using the tuple() constructor: tuple([1, 2, 3]) converts a list to a tuple.

Immutability means you cannot add, remove, or change elements of a tuple after creation. Attempting to assign to a tuple index (my_tuple[0] = 99) raises a TypeError. However, if a tuple contains mutable objects (like a list), those inner objects can still be modified. The tuple only guarantees that the references it holds do not change, not that the referenced objects themselves are frozen.

Tuple packing and unpacking are elegant features. Packing is when Python automatically bundles multiple comma-separated values into a tuple: coordinates = 3, 4 creates the tuple (3, 4). Unpacking does the reverse: x, y = coordinates assigns 3 to x and 4 to y. Unpacking works with any iterable, and you can use the * operator to capture remaining elements: first, *rest = (1, 2, 3, 4) gives first=1 and rest=[2, 3, 4]. Unpacking is used everywhere: multiple return values, swapping variables, and loop destructuring.

Named tuples from the collections module give your tuples field names, making code self-documenting. Instead of accessing elements by cryptic integer indices, you use descriptive attribute names: point.x instead of point[0]. Named tuples are lightweight, memory-efficient alternatives to full classes when you just need a simple data container. They remain immutable and fully compatible with regular tuples, supporting indexing, iteration, and unpacking.

Code examples

Creating Tuples

# Various ways to create tuples
empty = ()
single = (42,)        # Note the trailing comma!
not_a_tuple = (42)    # This is just an int
coords = (3, 4, 5)
from_list = tuple([1, 2, 3])

print(type(empty))
print(type(single), single)
print(type(not_a_tuple), not_a_tuple)
print(coords)
print(from_list)

A single-element tuple needs a trailing comma. Without it, parentheses are just grouping operators. The tuple() constructor converts any iterable to a tuple.

Immutability

colors = ("red", "green", "blue")

# Tuples support indexing and slicing
print(colors[0])
print(colors[-1])
print(colors[1:])
print(len(colors))

# But they cannot be modified
try:
    colors[0] = "yellow"
except TypeError as e:
    print(f"Error: {e}")

Tuples support reading operations like indexing, slicing, and len(), but any attempt to modify their contents raises a TypeError.

Packing and Unpacking

# Packing: commas create a tuple
point = 10, 20
print(point)

# Unpacking: assign tuple elements to variables
x, y = point
print(x)
print(y)

# Swap variables using unpacking
a, b = 5, 10
a, b = b, a
print(a, b)

# Extended unpacking with *
first, *middle, last = (1, 2, 3, 4, 5)
print(first)
print(middle)
print(last)

Tuple packing bundles values into a tuple. Unpacking extracts them into variables. The * operator collects remaining elements into a list. Variable swapping with a, b = b, a is a classic Pythonic pattern.

Named Tuples

from collections import namedtuple

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

print(p)
print(p.x)
print(p.y)
print(p[0])

# Named tuples are still tuples
print(isinstance(p, tuple))

# Convert to dictionary
print(p._asdict())

Named tuples add field names to tuples, making code more readable. They support both attribute access (p.x) and index access (p[0]). The _asdict() method converts them to an OrderedDict.

Key points

Concepts covered

Tuples, Immutability, Tuple Packing, Tuple Unpacking, Named Tuples