2. Immutability

A tuple is immutable: after you create it, its elements cannot be replaced, added or removed. This is the key difference from a list: a list changes in place, a tuple does not. Assigning to an index raises TypeError:

Tuples have no append(), remove() or sort() methods. The read-only methods are count() and index():

  • count(value) — how many times value appears.
  • index(value) — the position of the first value; raises ValueError when it is missing.

You can still build a new tuple. + joins two tuples and * repeats one:

Rebinding a variable is not mutation: point = (3, 4) makes the name point to a different tuple; the old tuple is unchanged.

The rule protects the tuple slots, not the objects inside them. If a slot holds a mutable object, such as a list, that object can still change:

#01

Try to change a tuple

Tuples are immutable, so assigning to one of their indexes fails. Create point = (1, 2, 3) and then assign 10 to index 0. Running the code must stop with:

Create a free account to save your progress and unlock chapter 2.

#02

Join tuples with +

The + operator joins two tuples into a new one; neither original tuple changes. Create base = (1, 2) and extra = (3, 4), then print base + extra.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Repeat a tuple with *

The * operator repeats a tuple. Print ("a", "b") * 2.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Rebind, do not mutate

Rebinding a variable is allowed: the name points to a new tuple. Create point = (1, 2), print it, then assign (3, 4) to point and print it again.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#05

Count occurrences

tuple.count(value) returns how many times value appears in the tuple. Print the number of times 2 appears in (1, 2, 2, 3, 2).

Print exactly:

Create a free account to save your progress and unlock chapter 2.