Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 77 ยท Python Interview Questions

Python: Mutability, Identity and the Data Model

Answer Python interview questions on is vs ==, mutable default arguments, shallow vs deep copy, hashability and dunder methods, with runnable examples.

Python interviews love questions that look innocent and hide one rule of the language: "Why did my default list keep growing?", "Why can't I use a list as a dictionary key?", "What is the difference between is and ==?" All of them come from the same idea: Python variables are names that point to objects, and objects are either mutable or immutable.

This lesson gives you short, accurate answers with code you can run. For the full lessons on these topics see membership and identity, copy and deepcopy, special methods and memory management. To structure what you say out loud, use A Framework for Answering Any Question.

Names, objects, values

Name A label that points to an object.
Object Has an identity, a type and a value.
Identity Compared with is. Shown by id().
Equality Compared with ==. Defined by eq.
1 / 2

is versus ==

== asks "do these two objects have equal values?" and calls __eq__. is asks "are these the very same object?" and compares identities. Use is for None (x is None) and rarely for anything else.

Python Same value, different object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Warn the interviewer that results like 256 is 256 being True depend on CPython's internal caching of small integers and some strings. You should never rely on it; compare numbers and strings with ==.

Mutable and immutable types

Immutable: int, float, bool, str, tuple, frozenset, bytes. Mutable: list, dict, set, bytearray, and most user-defined objects. "Immutable" means the object itself cannot change; x += 1 on an int rebinds the name to a new object.

A tuple is immutable but can contain mutable objects. Its references cannot change, though what they point to can.

Python Tuples with mutable contents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The += case is a famous follow-up: the in-place list extension succeeds first, and only then does Python try to store the result back into the tuple and fail. The list is changed even though an exception was raised.

The mutable default argument trap

Default values are evaluated once, when the function is defined, not on every call. A mutable default is therefore shared by all calls.

Python The shared default list and its fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The standard fix is None as a sentinel and creating the list inside the function. Immutable defaults (numbers, strings, None, tuples) are safe.

Copying: assignment, shallow, deep

Assignment (b = a) copies nothing; it adds a second name. A shallow copy (a.copy(), a[:], list(a), copy.copy(a)) creates a new container whose items are the same objects. A deep copy (copy.deepcopy(a)) copies the items recursively.

Python Assignment, shallow and deep copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Hashability

An object is hashable if it has a hash value that never changes during its lifetime and can be compared for equality. Dictionary keys and set members must be hashable. Immutable built-ins (str, int, tuple of hashables) are; lists, dicts and sets are not. The rule linking the two methods: objects that compare equal must have equal hashes.

Python Why lists are not dictionary keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

If you define __eq__ without __hash__, Python sets __hash__ to None, making the class unhashable. Hashing only fields that do not change keeps the rule safe; mutating a hashed field after inserting the object into a set or dict breaks lookups.

Dunder methods

"Dunder" (double underscore) methods let your classes plug into Python's syntax and built-ins. The questions you meet most are __repr__ versus __str__, __eq__/__lt__, __len__, __iter__, __getitem__, __enter__/__exit__ and __call__.

Python A small class that behaves like a built-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Say why __add__ returns NotImplemented rather than raising: it lets Python try the other operand's __radd__ before giving up. Containers like lists print the __repr__ of their items, which is why [price] shows Money(449).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a is b test?

    is compares identity. Value equality is what == does through eq.
  2. 2. Why does def f(x, items=[]) surprise people?

    The default is built when the def statement runs. Use None and create the list inside the function.
  3. 3. Which of these can be a dictionary key?

    Tuples of hashable items are hashable. Lists, sets and dicts are mutable and therefore unhashable.
  4. 4. What happens to __hash__ if a class defines __eq__ but not __hash__?

    Python assumes equal objects need equal hashes, so without an explicit hash the class becomes unhashable.

Summary

  • Names point to objects; is compares identity, == compares values.
  • Mutable objects change in place; immutable ones are replaced. A tuple can still hold mutable items.
  • Default arguments are evaluated once, so use None for mutable defaults.
  • Shallow copies share nested objects; copy.deepcopy copies them too.
  • Hashable objects have a stable hash and consistent equality; __eq__ and __hash__ go together.
  • Dunder methods connect your classes to operators and built-in functions.

Next: Python: Iterators, Generators and Comprehensions.