Guide Python Intermediate

11.13 Common Mistakes

The most common tuple bugs -- forgetting the trailing comma on a single-element tuple, trying to modify a tuple like a list, and being surprised that a nested mutable object inside a tuple can still change.

2 min read

Single-Element Tuple

Forgetting the trailing comma — (1) is an int, not a tuple (see 11.2 Creating Tuples). This silently produces the wrong type instead of raising an error, making it an easy bug to miss.

>>> not_a_tuple = (1)
>>> type(not_a_tuple)
<class 'int'>
>>> actual_tuple = (1,)     # comma required
>>> type(actual_tuple)
<class 'tuple'>

Modifying Tuples

Attempting to assign to an index, as if it were a list — always raises TypeError.

>>> t = (1, 2, 3)
>>> t[0] = 99
Traceback (most recent call last):
TypeError: 'tuple' object does not support item assignment

Nested Mutable Objects

Assuming a tuple is fully immutable, then being surprised that a nested list inside it can still be modified (see 11.8 Nested Tuples) — the tuple’s immutability is shallow, not deep.

>>> t = (1, [2, 3])
>>> t[1].append(4)     # allowed -- the inner list is still mutable
>>> t
(1, [2, 3, 4])

Quick Interview Answer

“Three mistakes account for most tuple bugs: forgetting the trailing comma on a single-element tuple, which silently produces the wrong type instead of erroring; trying to assign to an index like it’s a list, which correctly raises TypeError — that one’s rarely a silent bug, just a stumbling block for people newer to the type; and assuming immutability is deep, then being confused when a nested list inside a tuple changes anyway. That last one is the most conceptually important, since it reveals what ‘immutable’ actually means for a container type — the slots are frozen, not everything reachable through them.”

Common Mistakes

  • Writing config = (value) intending a one-element tuple and later iterating over it, hitting a TypeError because config turned out to be whatever type value already was.
  • Trying t.remove(x) or t[i] = x on a tuple used for config data, discovering only at runtime that the “list-like” object doesn’t support the mutation.
  • Passing a tuple containing a list to something expecting a hashable key (a dict key, a set element) and hitting TypeError: unhashable type: 'list' instead of catching it during design.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form