Python Glossary Русский

all Python 3Tuples (tuple)term

Tuple immutability

immutability

Tuples are immutable: an item cannot be changed, added or removed. Ways around it: build a new tuple, or convert it to a list.

Syntax

t[i] = val  # TypeError

The immutability is shallow: a tuple freezes its references, not the objects behind them, so if it holds a list, t[0].append(4) works fine. That is also why hashability depends on the contents — a tuple can be a dict key or a set member only if every element inside is hashable. The classic trap is t[0] += [4] on a nested list: the list really does grow, and only then does the assignment step raise TypeError.

Examples

t = (1, 2, 3)
try:
    t[0] = 99
except TypeError as e:
    print(e)  # → 'tuple' object does not support item assignment
try:
    del t[0]
except TypeError as e:
    print(e)  # → 'tuple' object doesn't support item deletion
t = (1, 2, 3)
t2 = t + (4,)
print(t2)  # → (1, 2, 3, 4) — новый кортеж, t не изменился
lst = list(t)
lst[0] = 99
t = tuple(lst)
print(t)  # → (99, 2, 3) — через список
nested = ([1, 2], [3, 4])
nested[0].append(5)
print(nested)  # → ([1, 2, 5], [3, 4]) — вложенный список изменяем!

See also

Open in the full glossarydocs.python.orgReport an inaccuracy