IntermediateLesson firstCategory 1 of 20

Tuples & Immutability

Work with immutable sequences. Read the lesson first, then move through the exercises in order.

13 Sections5 Exercises

After reading

Practice Arena

Begin with the first exercise, then continue step by step through the module.

Start with Data Unpacking

Study Material

Read the full lesson

What a tuple is

A tuple is an ordered group of items, just like a list, but you cannot change it after you create it. That rule is called immutability. Immutability makes your data safer because the values will not be edited by accident.

When to choose a tuple

Use a tuple when the values should stay fixed, such as:

  • A point like (x, y)
  • An RGB color like (255, 128, 0)
  • Days of the week

Use a list when you need to add, remove, or reorder items.

Creating tuples

You make tuples with parentheses and commas.

python
point = (3, 7) color = (255, 128, 0) empty = () from_list = tuple([1, 2, 3])

The one-item tuple

A tuple with one item must have a trailing comma. Without the comma, Python sees only a normal value in parentheses.

python
single = (42,) not_a_tuple = (42)

Reading and slicing

Tuples use the same indexing rules as lists.

python
numbers = (10, 20, 30, 40) print(numbers[0]) # 10 print(numbers[-1]) # 40 print(numbers[1:3]) # (20, 30)

Unpacking values

Unpacking assigns each position to a variable. The counts must match.

python
name, age = ("Lina", 28) x, y = (3, 7)

You can also capture the rest with a star.

python
first, *middle, last = (1, 2, 3, 4, 5) print(middle) # [2, 3, 4]

Swapping variables (tuples make it easy)

Tuple unpacking makes swapping simple and readable.

python
a, b = 1, 2 a, b = b, a

Returning multiple values from a function

Functions can return a tuple, which you can unpack right away.

python
def min_max(values): return min(values), max(values) low, high = min_max([3, 7, 2, 9])

Tuple methods you should know

Tuples are small but still have useful methods.

python
t = (1, 2, 1, 3) print(t.count(1)) # 2 print(t.index(3)) # 3

Tuples as dictionary keys

Because tuples are immutable, they can be used as dictionary keys. Lists cannot.

python
locations = {(0, 0): "origin", (1, 2): "point"} print(locations[(1, 2)])

Changing a tuple (the safe way)

If you must change it, convert to a list, edit, then convert back.

python
t = (1, 2, 3) items = list(t) items[0] = 99 t = tuple(items)

Common mistakes to avoid

  • Forgetting the comma in a one-item tuple.
  • Trying to change a tuple directly.
  • Unpacking into the wrong number of variables.

What you should understand after this lesson

  • What immutability means and why tuples are safe.
  • How to create tuples, including single-item tuples.
  • How to index, slice, and unpack tuples.
  • When a tuple is a better choice than a list.

Interactive

Exercises for this topic

These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.