Lesson 31 +10 XP

Identity Operators

Identity Operators

Identity operators check whether two values are the same object in memory: is and is not.

is vs ==

  • == compares the values.
  • is compares the objects themselves.
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x

print(x == z)  # True  (same values)
print(x is z)  # True  (same object)
print(x == y)  # True  (same values)
print(x is y)  # False (different objects)

Two lists with the same contents are == but not is.

is not

print(x is not y)  # True

The classic use: None

is None is the idiomatic way to test for None:

result = get_data()
if result is None:
    print("No data")

Small integers trick

Python reuses small ints, so 1000 is 1000 can be True in the same expression, but don't rely on it. Always use == for numbers.

TL;DR

  • is checks object identity; == checks value.
  • Two equal lists are == but not is.
  • Use is None for None checks.
  • For numbers and strings, use ==.