Python Tutorial · Data Structures · Lesson 16 of 42

Python Tuples

Immutable sequences, unpacking and returning several values from a function.

Creating tuples

A tuple is like a list but immutable. It's written with parentheses (or just commas).

Example 1Try it yourself
point = (3, 4)
colors = "red", "green", "blue"
single = ("apple",)
print(point[0], len(colors), type(single))
try:
    point[0] = 10
except TypeError as e:
    print("Error:", e)

Output

3 3 <class 'tuple'>
Error: 'tuple' object does not support item assignment

A one-item tuple needs a trailing comma: ("apple",) — without it, it's just a string in parentheses.

Unpacking

Tuples shine when you unpack them into variables — including swapping values without a temporary variable:

Example 2Try it yourself
x, y = (3, 4)
print(x, y)
a, b = 1, 2
a, b = b, a
print(a, b)
first, *rest = [1, 2, 3, 4]
print(first, rest)

def min_max(values):
    return min(values), max(values)
low, high = min_max([5, 2, 9])
print(low, high)

Output

3 4
2 1
1 [2, 3, 4]
2 9

When to use tuples

  • Fixed groups of values: coordinates (x, y), RGB colours, database rows.
  • As dictionary keys or set members (lists can't be, because they're mutable).
  • Returning several values from a function.

Test yourself

How do you write a tuple containing only the number 5?

  1. (5)
  2. (5,)
  3. [5]
  4. tuple 5
Show answer

Answer: (5,)