DEV Community

Samuel Ochaba
Samuel Ochaba

Posted on

Why Your Python Tuple Can't Be a Dictionary Key

"Tuples are immutable" is one of the first things you learn about Python tuples.

But check this out:

>>> t = ([1, 2], [3, 4])  # Tuple of lists
>>> t[0].append(99)        # Modify the list inside
>>> t
([1, 2, 99], [3, 4])      # It changed!
Enter fullscreen mode Exit fullscreen mode

Wait—didn't we say tuples can't be modified?

The tuple itself didn't change. It still contains exactly two references to the same two list objects. What changed is the content of one of those list objects.

Think of it like a display case with two fish tanks inside. You can't add or remove tanks from the case (the tuple is immutable), but the fish inside each tank can still swim around (the lists are mutable).

This has real consequences:

>>> t = ([1, 2], [3, 4])
>>> hash(t)
Traceback (most recent call last):
  ...
TypeError: unhashable type: 'list'
Enter fullscreen mode Exit fullscreen mode

Tuples containing mutable objects cannot be hashed—which means they can't be dictionary keys or set members.

Why this matters for AI engineering:

When you're working with embeddings, model outputs, or cached results, you might think "I'll use a tuple as a cache key." But if that tuple contains any mutable objects (lists, dicts, sets), you'll get a TypeError at runtime.

The fix: ensure all elements are also immutable:

# This works as a cache key
key = (model_name, tuple(input_ids), temperature)

# This fails
key = (model_name, input_ids, temperature)  # if input_ids is a list
Enter fullscreen mode Exit fullscreen mode

This is adapted from my upcoming book, Zero to AI Engineer: Python Foundations.
I share excerpts like this on Substack → https://substack.com/@samuelochaba

Top comments (0)