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()/isprove 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.