Identity Operator for Cache Hits

Medium ⏱ 12 min 64% acceptance ★★★★★ 4.5
Write a function is_cached(obj, cache) that returns True if obj is the exact same object (not merely an equal value) as any item currently in the list cache, using the is identity operator. This models a cache that stores object references and must distinguish "same instance" from "equal value" (e.g. two equal-looking dicts loaded separately should NOT count as cached).

Examples

Example 1
Input
x = {"id": 1}; cache = [x]; is_cached(x, cache)
Output
True
Explanation

x is literally the object stored in cache.

Example 2
Input
is_cached({"id": 1}, [{"id": 1}])
Output
False
Explanation

Equal values but distinct object instances — not a cache hit.

Constraints

  • cache is a list of arbitrary objects, possibly empty.

Topics

Operatorsidentity operators

Companies

GoogleMeta

Hints

Hint 1

Loop through cache and check `item is obj` for each, not `item == obj`.

Hint 2

The built-in `any()` combined with a generator expression can shorten this.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.