Skip to content

Tuples

A tuple ((1, 2, 3)) is an ordered sequence like a list, but immutable β€” once created, you can’t add, remove, or reassign its elements. Because they’re immutable, tuples are hashable (when their contents are), so they can be used as dictionary keys or set members, unlike lists.

point = (3, 4)
x, y = point # unpacking
coordinates = (10, 20, 30)
print(coordinates[0]) # 10
# coordinates[0] = 99 # TypeError: 'tuple' object does not support item assignment
# Common use: dict keys (tuples are hashable, lists aren't)
distances = {(0, 0): 0, (1, 1): 1.41}
def min_max(numbers):
return (min(numbers), max(numbers)) # returning multiple values as a tuple
low, high = min_max([4, 1, 9, 2]) # unpacked directly

Forgetting the trailing comma when creating a single-element tuple β€” (5) is just the integer 5 in parentheses, not a tuple.

not_a_tuple = (5)
print(type(not_a_tuple)) # <class 'int'>
actual_tuple = (5,) # the comma is what makes it a tuple
print(type(actual_tuple)) # <class 'tuple'>
  1. What makes (5,) a tuple but (5) just an integer?

    AnswerThe trailing comma β€” parentheses alone are just grouping syntax; the comma is what actually creates a tuple.
  2. Why can tuples be used as dictionary keys but lists can’t?

    AnswerTuples are immutable and hashable (as long as their contents are); lists are mutable and therefore unhashable, so they're not allowed as dict keys.
  3. What does x, y = (3, 4) do?

    AnswerTuple unpacking β€” it assigns 3 to x and 4 to y in one statement.