Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Understanding Tuples in Python: A Practical Guide

1 min read .
Understanding Tuples in Python: A Practical Guide

A tuple is an ordered Python collection whose item references cannot be reassigned after creation. Tuples are useful for fixed groups of related values, function return values, dictionary keys when their contents are hashable, and lightweight records.

Create Tuples

coordinates = (10, 20)
colors = ("red", "green", "blue")

The comma is what creates a tuple, not the parentheses alone. A one-item tuple therefore needs a trailing comma:

single = (42,)
not_a_tuple = (42)

Access Items

Tuples support indexing and slicing:

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

print(colors[0])
print(colors[-1])
print(colors[1:])

Tuples Are Immutable

This is not allowed:

point = (10, 20)
# point[0] = 99  # TypeError

However, immutability is shallow. A tuple can contain a mutable object whose contents can still change:

values = ([1, 2], "fixed")
values[0].append(3)
print(values)

The tuple still references the same list; the list itself was mutated.

Tuple Unpacking

Tuples work naturally with unpacking:

point = (10, 20)
x, y = point

Extended unpacking is also supported:

first, *middle, last = (1, 2, 3, 4, 5)

Return Multiple Values

Python functions commonly return tuples implicitly:

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


minimum, maximum = min_max([4, 2, 8, 1])

Concatenation and Repetition

left = (1, 2)
right = (3, 4)
combined = left + right
repeated = (1, 2) * 3

These operations create new tuples because existing tuples cannot be modified.

Membership

numbers = (1, 2, 3, 4, 5)

print(3 in numbers)  # True
print(6 in numbers)  # False

Tuples as Dictionary Keys

A tuple is hashable only when all of its elements are hashable:

locations = {
    (40.7128, -74.0060): "New York",
    (51.5074, -0.1278): "London",
}

A tuple containing a list cannot be used as a dictionary key.

Tuple or List?

Use a tuple when the collection represents a fixed record or should not be structurally modified. Use a list when you expect to add, remove, or replace items.

Conclusion

Tuples are compact, ordered collections for fixed groups of values. Their strengths are immutability, unpacking, and hashability when their contents allow it. Use them when the structure of the data is stable and a mutable list would communicate the wrong intent.

Related Posts

chevron-up