Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Core language & syntaxJuniorVery commonTheory

Which built-in types are mutable and which are immutable, and why does that distinction matter for function defaults and hashing?

Answer

list, dict, set and bytearray are mutable; int, float, str, tuple, frozenset and bytes are immutable. Most immutable built-ins are safe to hash and use as dict keys or set members because their value cannot change after creation, but an immutable container like a tuple is only hashable if every element it holds is itself hashable — a tuple containing a list, for example, is still unhashable. Mutability also explains the classic mutable-default-argument bug: a default like `def f(items=[])` creates one list object that is reused and mutated across every call that does not pass its own argument, because default values are evaluated once when the function is defined.

Strong answer includes

  • mutable vs immutable built-ins
  • immutable containers are hashable only if every element they hold is hashable too
  • mutable default argument pitfall

Practical example

Mutable default: bug and fix
Python
editable · browser sandbox
Result
Run the code to see the result.

The first function reuses one list created when the function is defined, so state leaks between calls. The safe version creates a fresh list for each call that omits bucket.

Expected result: The buggy calls print ['a'] then ['a', 'b']; the safe calls print ['a'] then ['b'].

#mutability#gotchas

Sources

The Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modulesData modelPython Software Foundation · Dunder methods, object identity, attribute lookup and the descriptor and context manager protocols