In this lesson, you will learn how to distinguish between checking if two variables have the same value versus checking if they are the exact same object in memory.
The Equality Operator (==)
When you use the == operator, Python checks for equality. It asks: "Do these two variables hold the same data?"
Think of it like checking two physical books: if they both contain the same story, they are equal. You don’t care if one is a hardback and one is a paperback; the content is what matters.
list_a = [1, 2, 3]
list_b = [1, 2, 3]
print(list_a == list_b) # True, because the content is the same
The Identity Operator (is)
The is operator checks for identity. It asks: "Are these two variables pointing to the exact same spot in the computer's memory?"
Even if two lists contain the same items, Python often creates two separate objects in memory when you define them independently. Using is is like checking if you are holding two different copies of the same book versus holding the exact same physical copy.
list_a = [1, 2, 3]
list_b = [1, 2, 3]
print(list_a is list_b) # False, they are two different objects in memory
Why the difference matters
In most cases, you want to use == because you are interested in the value of the data. However, there is one important exception where you should use is: checking for None.
In Python, None is a special object that represents the absence of a value. Because there is only ever one None in your program, it is idiomatic and safer to use is when testing for it:
user_input = None
if user_input is None:
print("No data provided yet.")
By understanding this distinction, you avoid confusing the "value" of an object with its "location" in your computer's memory.
Key Takeaway: Use == to compare if values are equivalent, and use is only when you need to verify if two variables refer to the exact same object in memory.