Course contentsShow
← Python
Lesson 22 of 1,0601. Foundations and EnvironmentFree lesson

Comparing Object Identity with the Is Operator

You will differentiate between value equality using the double equals operator and identity comparison using the is keyword.

In this lesson, you will learn how to distinguish between checking if two variables contain the same value and checking if they refer to the exact same object in your computer's memory.

Equality vs. Identity

So far, you have used the == operator to see if two variables hold the same value. For example, if you set a = 10 and b = 10, a == b evaluates to True because their values are identical. However, in Python, variables are just labels pointing to objects in memory. Sometimes, two labels point to different objects that happen to have the same data.

To check if two variables point to the exact same object in memory, we use the is operator.

Using the is Operator

Think of the is operator as a "memory address checker." It doesn't care what the value is; it only cares if the two labels are pointing to the same physical location.

Look at this example:

x = [1, 2, 3]
y = [1, 2, 3]

# Do they have the same value?
print(x == y)  # Result: True

# Do they refer to the same object in memory?
print(x is y)  # Result: False

In this code, Python creates two separate list objects in memory. Even though they contain the same numbers, they are distinct items. Therefore, x == y is True because their contents match, but x is y is False because they live at different memory addresses.

If you were to write z = x, then z would point to the same object as x. In that case, x is z would return True.

When to use which?

  • Use == when you want to know if two variables represent the same information (the value).
  • Use is when you need to confirm that two variables are exactly the same object in memory. (This is often used for special values like None).

Key Takeaway: The == operator checks if two variables have the same value, while the is operator checks if they point to the exact same object in memory.