Just starting out with Python, have you ever been puzzled by this: two values that look exactly the same return False when compared with is, but True when compared with ==? They both mean “equal,” so why the big difference?
Today, using the simplest language and everyday analogies, we’ll help you thoroughly understand how these two operators work. Say goodbye to headaches over this bug!
First, a simple analogy to instantly grasp the core difference
Let’s set code aside and use a real-life example:
You and a friend go to the library and both borrow the book “Python Basics”.
- The book in your hand and the book in your friend’s hand have exactly the same content (like two variables having the same value).
- But they are two different physical books, not the same one (like two variables pointing to different objects).
- If your friend simply hands you their book, then you are now holding the same physical book (like one variable being assigned to another).
In Python terms:
==: Only cares about “Is the content the same?” (Are the words in the two books identical?)is: Only cares about “Is it the same physical thing?” (Is this the exact same physical book?)
Let’s feel it with a simple code snippet:
python
# Two copies of "Python Basics" with the same content. book1 = "Python Basics" book2 = "Python Basics" # Directly give book1 to book3. book3 = book1 print(book1 == book2) # True → Content is the same. print(book1 is book2) # False → Not the same physical book. print(book1 is book3) # True → It is the same physical book.
Technical Breakdown: What Exactly Are They Comparing?
1. is: Checking “Identity” (Is it the same object?)
is is like checking two people’s ID numbers—if the ID numbers are the same, they are definitely the same person. If different, no matter how similar, they are different people.
In Python, every object has a unique “ID number”—its memory address, which you can view with the id() function.
python
a = [1, 2, 3]
b = a # Give b the same "ID number" as a.
c = [1, 2, 3] # Create a new list, gets a new "ID number".
print(f"Memory address of a: {id(a)}") # e.g., Output: 140688907250240
print(f"Memory address of b: {id(b)}") # Exactly the same as a's.
print(f"Memory address of c: {id(c)}") # A completely different number.
print(a is b) # True → Same ID number, same object.
print(a is c) # False → Different ID numbers, different objects.
In short: is compares whether two variables point to the same object in memory.
2. ==: Checking “Content” (Are the values equal?)
== is like comparing two people’s appearance and personality—even if they are not the same person, as long as these traits match, they are considered “equal.”
It doesn’t care if the two variables are the same object; it only checks if their contents match.
python
x = [1, 2, 3] y = [1, 2, 3] # A new object, but its content is the same as x's. print(x == y) # True → Contents are equal. print(x is y) # False → Not the same object.
Must-Know for Beginners: When to use is? When to use ==?
1. 3 Scenarios for using is (Memorize these!)
- Check if something is
None(Most common!):python# Correct way (Recommended by Python official docs) if data is None: print(“Data is empty.”) # Wrong way (Don’t do this!) # if data == None: # print(“Data is empty.”)Reason: There is only oneNoneobject in Python. Usingisis the safest and won’t cause surprises. - Check if something is
TrueorFalse(Singleton objects):pythonflag = True if flag is True: print(“Execution successful.”) - Verify if they are the same object:
For example, confirming if two variables point to the same list (so modifying one affects the other).
2. All scenarios for using == (Use it for comparing values!)
- Compare numbers:
age == 18,score == 100 - Compare strings:
name == "Xiao Ming",password == "123456" - Compare containers like lists/dicts:
list1 == [1,2,3],dict1 == {"name": "Xiao Hong"}
Simple Mnemonic: is checks identity, == checks content.
Python’s Optimization: Why does is sometimes return True in these cases?
Beginners might encounter a strange phenomenon: sometimes variables created separately compare True with is? This is due to Python’s optimization mechanisms. Just remember it; no need to dive deep into the why.
1. Small Integer Caching (-5 to 256)
Python caches commonly used small integers for reuse, so is will also be True for these numbers:
python
a = 100 b = 100 print(a is b) # True (Within cache range) c = 1000 d = 1000 print(c is d) # False (Outside cache range)
2. Simple String Interning
Simple strings (without special characters) are “remembered” by Python and reused when created again:
python
s1 = "hello" s2 = "hello" print(s1 is s2) # True s3 = "hello python!" # Contains a space/special char, not interned. s4 = "hello python!" print(s3 is s4) # False
The 2 Most Common Beginner Pitfalls!
Pitfall 1: Using is to compare values
python
# Wrong example (Results are unpredictable!)
x = 1000
y = 1000
if x is y:
print("Equal")
# Correct way (Always use == to compare values)
if x == y:
print("Values are equal")
Pitfall 2: Assuming containers with the same content are the same object
Containers like lists and dictionaries are different objects even if their contents are identical. Modifying one won’t affect the other.
python
list1 = [1, 2, 3] list2 = [1, 2, 3] print(list1 == list2) # True (Same content) print(list1 is list2) # False (Different objects) list1.append(4) print(list1) # [1, 2, 3, 4] print(list2) # [1, 2, 3] (Unchanged)
Summary: Remember these 4 rules and you’ll never fall into these traps again.
- To check if something is
None, useis None(Not== None). - To compare if two values are equal, use
==(Notis). - Only use
iswhen you specifically want to confirm if it’s the same object. - When in doubt, use
==. You’ll most likely be correct.
Finally, a practical example to solidify your understanding:
python
def check_user(user, expected_name):
# First, check if the object is empty.
if user is None:
return False
# Then, compare the content (username).
if user.name == expected_name:
return True
return False
So, do you completely understand the difference between is and == now? Python’s design is actually quite logical. Each operator has its own role. Just remember “is checks identity, == checks content,” and you’ll never step into these potholes again!