L2 · Working engineerPython internals~3 min · 4 tests#67

is vs == in Python

Learn the difference between Python's is (same object) and == (equal value) with lists, None and small integers. Write it and prove it with tests.

The problem

Write compare(a, b) that returns a dict {"equal": …, "identical": …}:

  • "equal" — do they have the same value (==)?
  • "identical" — are they the same object (is)?

Examples

  1. Example 1

    Input

    compare([1, 2, 3], [1, 2, 3])

    Expected output

    {'equal': True, 'identical': False}
  2. Example 2

    Input

    (lambda x: compare(x, x))([1])

    Expected output

    {'equal': True, 'identical': True}

+ 2 hidden tests on Submit.

Edge cases to ask about

  • None
  • Same object
  • Small-int caching (never rely on it)

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · compare
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    == calls __eq__; is compares identityO(n) for ==, O(1) for isO(1)
    Walkthrough of the optimal approach (try it yourself first)

    == calls __eq__ and compares values; is compares identity (same object). Two lists built separately are == but not is.

    Use is only for singletons: x is None, x is True. Never use it for numbers or strings — 256 is 256 happens to be True because CPython caches small ints, but larger values may not be, so code that relies on it breaks unpredictably.

    Complexity: O(1) time, O(1) space. `is` is a pointer comparison; `==` on lists compares element by element (O(n)).

    Reveal the reference solution
    def compare(a, b):
        return {"equal": a == b, "identical": a is b}

    Follow-ups interviewers ask

    • Why is x is None preferred over x == None?
    • What does id() return?

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of is vs == in Python?

    The optimal solution runs in O(1) time and O(1) auxiliary space. is is a pointer comparison; == on lists compares element by element (O(n)).

    What follow-up questions do interviewers ask about is vs == in Python?

    Why is x is None preferred over x == None? What does id() return?