download

Why did your object vanish from a set after you changed it?

Algorithms~10 minReviewed 1 Nov 2026Free · No sign-in

Question

A shopping cart is a set of Product objects. Two products are equal when they have the same sku. The code changes the sku of a product that is already in the cart, and then the cart can't find it.

What do the three print lines show, and why? Then change Product so this bug can't happen.

"CODE · PYTHON"
class Product:
    def __init__(self, sku, name):
        self.sku = sku
        self.name = name

    def __eq__(self, other):
        return isinstance(other, Product) and self.sku == other.sku

    def __hash__(self):
        return hash(self.sku)


cart = {Product(101, "mug")}
item = next(iter(cart))
item.sku = 202
print(item in cart)
print(Product(101, "mug") in cart, Product(202, "mug") in cart)
print(len(cart))
Show hints (3)
  1. "FILED UNDER"

    A set files each item under its hash when you add it. It doesn't notice when the object changes later. Which hash did the mug have when it went in?

  2. "TWO DIFFERENT MISSES"

    item in cart now uses hash(202), so it looks in a different place. Product(101, "mug") looks in the right place. But is it still equal to the stored mug?

  3. "FREEZE THE KEY"

    A key must not change while it is in a set or a dict. Make Product immutable with @dataclass(frozen=True), and let only sku count for == and the hash.

Show checked explanation

It prints False, then False False, then 1. The set stored the mug under hash(101). Changing sku changed its hash, but the set didn't move it. So every search misses, though the mug is still inside. Equal objects need equal hashes, and the hash of a key must not change. Make the key fields immutable.

"SOLUTION · PYTHON"
from dataclasses import dataclass, field


@dataclass(frozen=True)
class Product:
    sku: int
    name: str = field(compare=False)  # not part of == or the hash


cart = {Product(101, "mug")}
item = next(iter(cart))
try:
    item.sku = 202
except AttributeError as error:
    print(type(error).__name__)
print(Product(101, "cup") in cart, len(cart))
"OUTPUT"
FrozenInstanceError
True 1

Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.

Walkthrough

A set is a hash table, like a dict without values. cart = {Product(101, "mug")} calls hash(101) and stores the mug in the place that hash points to. Then item.sku = 202 changes the object, but nothing tells the set. The mug stays where hash(101) put it.

searchwhere the set looksresult
item in cartthe place for hash(202)nothing there, False
Product(101, "mug") in cartthe place for hash(101)finds the mug, but its sku is now 202, so == fails: False
Product(202, "mug") in cartthe place for hash(202)nothing there, False

The mug is still inside. len(cart) is 1, and a loop over the cart shows it. But no search reaches it, and cart.remove(item) raises KeyError.

The Python docs give the rule: objects that compare equal must have the same hash. A set or a dict also needs the hash of a stored key to stay the same. So a field used by __eq__ and __hash__ must not change while the object is a key.

@dataclass(frozen=True) makes the object read-only. Assigning to a field raises FrozenInstanceError, which is a kind of AttributeError. The dataclass writes __eq__ and __hash__ for you from the fields. field(compare=False) leaves name out of both. So products with the same sku are equal even when the names differ, and Product(101, "cup") in cart is True.

If you keep a mutable class, take the object out before you change it, then add it back:

"PYTHON"
cart.remove(item)
item.sku = 202
cart.add(item)

Now the mug is stored under hash(202), and item in cart is True.

Common mistakes

  • Defining __eq__ and forgetting __hash__. Python then sets __hash__ to None, and {Product(101, "mug")} raises TypeError: unhashable type: 'Product'.
  • Silencing that error with __hash__ = object.__hash__. The hash then comes from the object's identity, so two equal products get different hashes. A set keeps both, and len is 2 instead of 1.
  • Hashing by adding fields: return hash(self.store + self.sku). It is legal, but store 1 with sku 2 and store 2 with sku 1 always collide. Hash a tuple instead: hash((self.store, self.sku)).
  • Hashing a field that changes, like price. Each price change hides the object again. Only hash fields that stay fixed while the object is in a set or a dict.

Follow-up questions

  • "d = {1: "a", 1.0: "b", True: "c"}. How many keys does d have?" One. 1 == 1.0 == True, and Python gives equal numbers equal hashes, so all three are the same key. The dict keeps the first key object and takes the last value: d is {1: 'c'}.
  • "Why can't you use a list as a dict key?" A list can change, so list sets __hash__ to None, and hash([1, 2]) raises TypeError. If a list key could change, you would get this exact bug. Use a tuple, such as (store, sku), or a frozen dataclass.

What a strong answer covers

Predicts all three results and explains each with the hash the set used. States the rule: equal objects have equal hashes, and a key's hash must not change. Fixes it with a frozen dataclass, and knows that __eq__ without __hash__ makes a class unhashable.

Open in interactive practice deck →

Original OfferVibe question. Topic idea from Crushing the Technical Interview (Keith Henning, 2025); text, examples and code are our own.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.