Skip to the solution
EasyDSA10 min read

What are mutable and immutable types in Python?

1.1k views

The problem

Question presented to candidate: "Python talks a lot about mutable and immutable objects. What does that actually mean, which built-in types fall on each side, and where does the difference cause real bugs?"

What a strong answer should cover:

  • Mutable objects can change in place (list, dict, set, bytearray, most class instances); immutable ones cannot (int, float, bool, complex, str, bytes, tuple, frozenset, range, None), so every "change" builds a new object.
  • Assignment binds a name to an object and never copies, so two names can alias one mutable object; rebinding a name is not mutating an object.
  • += mutates a list in place but rebinds a name for a tuple or int; id() / is prove which happened.
  • Immutability is shallow: a tuple can hold a list, and is then unhashable; the t[0] += [x] gotcha both mutates and raises.
  • Consequences: hashability and dict keys, functions changing the caller argument, the mutable default argument bug, thread-safety and caching benefits of immutables.

Code / implementation expected: Optional β€” a short snippet showing aliasing and += on a list vs a tuple is a strong addition.

  • mutability

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonAliasing vs rebinding, and += on a list vs a tuple
PythonShallow immutability, the tuple += gotcha and function arguments

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 3 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

How do you work with dictionaries (get, setdefault, items, merging)?

Continue