Equality is a core concept in programming. As a Python developer, you‘ll often need to check if two values are equal or not equal.
In this comprehensive guide, you‘ll learn:
- How to use Python‘s
!=
and==
operators to test for inequality and equality - The difference between comparing values and object identity
- When to rely on
==
versus theis
operator - Best practices for equality testing in Python
Let‘s dive in!
The Not Equal Operator (!=)
We‘ll start with Python‘s not equal operator, !=
. Here‘s a quick example:
num1 = 5
num2 = 10
print(num1 != num2) # True
The !=
operator compares two objects. If their values are different, it returns True
. Otherwise it returns False
.
Some key properties of !=
:
- Works with all basic data types: numbers, strings, booleans, etc.
- Also works for comparing collections like lists, dicts, sets, tuples
- Returns opposite boolean result of the
==
equal operator
Let‘s look at some more examples of using !=
…
# Comparing strings
print("cat" != "dog") # True
# Lists with different elements
a = [1, 2]
b = [3, 4]
print(a != b) # True
# Dicts with diff key-value pairs
x = {"name": "John"}
y = {"name": "Jane"}
print(x != y) # True
As we can see, !=
gives us an easy way to check if two Python objects differ in value.
Next let‘s go over the equal operator.
The Equal Operator (==)
The equal operator ==
compares two objects and returns True
if they are equal, False
otherwise:
print(5 == 5) # True
print([1,2] == [1,2]) # True
x = "hello"
y = "hello"
print(x == y) # True
Here are some key details on using ==
:
- Works for all data types like
!=
- Returns opposite boolean result of
!=
- Does not perform type coercion – 5 and "5" are NOT equal
- Compares values rather than object identity (contrast with
is
operator)
Since ==
does not do type conversion, you need to be careful when comparing different data types:
print(5 == "5") # False - int vs string
nums = [1, 2, 3]
print(nums == (1, 2, 3)) # False - list vs tuple
So while 5
and "5"
may look equal at first glance, they are different underlying data types.
Let‘s go over some examples of using ==
in conditional statements, loops, and list/dict comprehensions…
nums = [1, 3, 5]
# Check for even numbers
for num in nums:
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
# Filter list for only even numbers
evens = [x for x in range(10) if x % 2 == 0]
print(evens)
# Key check in dict
person = {"name": "Mary", "age": 25}
if person["name"] == "Mary":
print("Found correct person!")
There are some best practices around using ==
effectively:
- Be purposeful about what objects you are comparing
- Watch out for edge cases like empty strings, zeros, None values
- Handle floating point rounding errors and approximations (e.g. round values before comparing)
And that covers equality testing with Python‘s ==
operator! 🎉 Next let‘s contrast it with Python‘s is
operator for testing identity…
Comparing Identity: Python‘s is
vs ==
Python has two ways to check if objects are equal:
==
compares valuesis
compares object identity
This leads to some key differences in behavior between is
and ==
.
Consider two strings with the same value:
a = "pythön"
b = "pythön"
print(a == b) # True, values are equal
print(a is b) # False, objects have different identity
Even though a
and b
have the same value, they reference two different string objects in memory.
The id()
function returns an object‘s identity as an integer:
print(id(a)) # 45570224
print(id(b)) # 45570176
Since those identity numbers differ, a is b
evaluates to False.
In contrast, when two variables reference the exact same object, is
returns True:
x = ["apple", "banana"]
y = x
print(x is y) # True, x and y reference the SAME list object
To summarize:
- Use
==
to check if two objects have the same value - Use
is
to check if two references point to the same object
Here are some key differences:
== |
is |
---|---|
Checks value equality | Checks identity |
Returns True if values match | Returns True only if both vars reference same object |
Works across data types | Can sometimes return unexpected False if values look equal |
Runs equality check logic | Faster since only checks object reference |
When should you use is
vs ==
?
- Prefer
==
in most cases – easier to reason about - Use
is
when you specifically need to check object interning or identity is
tends to appear mostly in low level optimization scenarios to eke out performance gains
Hopefully this explains how to properly leverage Python‘s ==
and is
operators!
Additional Examples and Practice
And now let‘s go through some more nitty gritty examples to really solidify your knowledge…
I‘ll show you how to use ==
and !=
:
- With custom classes…
- In chained comparisons…
- To write Python one-liners…
- To test function outputs…
And more. These examples showcase just how versatile Python‘s equality operators can be!
# Case 1: Chained Comparisons
age = 18
print(18 <= age < 65) # Check if in range - True
# Case 2: Custom Class Equality
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 30)
p2 = Person("John", 30)
print(p1 == p2) # False - compares object identity
# Define equality check method
def __eq__(self, other):
if isinstance(other, Person):
return self.name == other.name and self.age == other.age
return False
print(p1 == p2) # Now True! Custom equality check
# Case 3: One-liner function to test if list has duplicates
has_dups = lambda x: len(set(x)) != len(x)
vals = [1, 2, 3, 2]
print(has_dups(vals)) # True
# Case 4: Test output of math functions
import math
print(math.isnan(5) == False) # 5 is valid number, not NaN
print(math.isinf(10 / 0)) # True, inf result
I hope these diverse examples give you ideas for how to leverage equality operators in your own code!
Summary: Key Takeaways
We‘ve covered a ton of ground on equality testing in Python. Let‘s review the key takeaways:
- Use
!=
to check if two objects do not have the same value - Use
==
to check if two objects do have the same value - Remember –
==
compares values,is
compares object identity reference - Prefer
==
in most cases, fall back tois
for optimizations - Implement
__eq__
in classes to enable custom equality checks - Use
==
and!=
extensively when writing conditional code
Equality operators come up all the time in Python programming. I hope this guide gives you an in-depth understanding so you can use ==
and !=
effectively!
For more coding tutorials and Python tips, check out:
Happy coding!