Q&A library Python

What is the difference between is and == in Python?

Python Beginner comparisonequalityidentity

Short answer

== checks whether two values are equal, while is checks whether they are the exact same object in memory. Use == for value comparisons and reserve is for checks against None.

The short version

== asks whether two things have equal values. is asks whether they are literally the same object in memory. These usually agree, which hides the difference, but they are answering different questions. Use == for comparing values and reserve is for identity checks, above all is None.

Seeing them differ

a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)   # True: same contents
print(a is b)   # False: two separate lists
print(c is a)   # True: c is another name for the same list

a and b hold equal values, so == is True, but they are distinct objects, so is is False. c was assigned from a, so they are the same object and is is True.

Why is None is the right idiom

The one place is is clearly correct is testing for None, because there is only ever one None object in a program. Identity is exactly what you mean.

if value is None:
    ...

This is preferred over value == None, partly for clarity and partly because a custom object could define == to behave oddly, whereas is None cannot be fooled.

The trap with small integers and short strings

Python reuses (caches) some small integers and short strings, so is sometimes returns True for equal values by coincidence.

x = 100
y = 100
x is y      # often True, but an implementation detail

Never rely on this. It is a memory optimisation, not a promise, and it does not hold for larger numbers. If you write if x is 100 it may work today and fail elsewhere. Modern Python even warns you about using is with a literal, because it is almost always a mistake.

The rule to keep

Compare values with ==. Use is only to compare identity, in practice almost always is None or is not None. If you are checking whether two variables happen to point at the very same object, is is right; for everything else, use ==.

Need this solved on your own data?

The library is free and always will be. When the problem is bigger than an answer, we take on the work.

Start a project