Python Equal To

5/5 - (1 vote)

The Python equal to (left==right) operator returns True when its left operand is equal to its right operand. Otherwise, it returns False. For example, 3==3 evaluates to True, but 3==2 evaluates to False.

Python Equal To Operator Deep Dive

Examples

Let’s explore a couple of examples regarding the equal to operator.

Is 3 equal to 2?

>>> 3 == 2
False

What about 'h' equal to 'h'?

>>> 'h' == 'h'
True

Can you compare collections such as lists, strings, tuples?

>>> [1, 2] == [1, 2]
True
>>> [1, 2] == [1, 2, 3]
False
>>> (1, 1) == (1, 1, 1)
False
>>> 'hello' == 'hello'
True

Yes!

The list equal to operator iterates over the lists and checks pairwise if the i-th element of the left operand is equal to the i-th element of the right operand.

Can you use the equal to operator on custom objects? Yes!

Python Equal to on Custom Objects

To use the equal to operator on custom objects, you need to define the __eq__() “dunder” magic method that takes two arguments: self and other. You can then use attributes of the custom objects to determine if one is equal to the other. It should return a Boolean True or False.

In the following code, you check if a Person is equal to another Person by using the age attribute as a decision criterion:

class Person:
    def __init__(self, age):
        self.age = age

    def __eq__(self, other):
        return self.age == other.age



alice = Person(18)
bob = Person(19)
carl = Person(18)

print(alice == bob)
# False

print(alice == carl)
# True

Because Alice is 18 years old and Bob is 19 years old, the result of alice == bob is False. But the result of alice == carl evaluates to True as both have the same age.

Python Equal to Multiple Values

How do you check if a value is equal to multiple values?

To check if a finite number of values are equal, you can chain the comparison operator == multiple times. For example, the expression x == y == z evaluates to True if all three are equal. This is a shorthand expression for (x == y) and (y == z).

In the following example, you create three variables that all get assigned the same value 42. When checking them using x == y == z, the result is True.

>>> x = 43 - 1
>>> y = 42
>>> z = 21 + 21
>>> x == y == z
True

Python Equal to A or B

To check if value x is equal to either a or b or both, you can use the expression x in {a, b}.

  • By putting the values into a set {a, b}, you can essentially perform a logical or operation on equality testing.
  • You check membership by using the keyword in. This checks in a performant way (constant runtime complexity!) whether value x exists in the set, i.e., the equality operator evaluates to True.

Here’s a minimal example where we create a value x and check if it is equal to a or b by putting both into a set and checking membership:

>>> x = 42
>>> a = 21 + 21
>>> b = 43 * 2
>>> x in {a, b}
True

The value 42 exists in the set—x is equal to a in the example. So the result is True.

Python Equal to OR

To check if value x is equal to multiple values, i.e., performing a logical or operation on equality testing, you can put all values to test against in a set S. Then, check x in S to test if any value y in the set S is equal to variable x.

Here’s a minimal example where we perform a logical or on x == y for all values y by converting the list of values into a set for efficiency reasons. Checking membership using the in keyword is more efficient on sets than on lists.

>>> lst = ['alice', 42, 'finxter', 21, 333, None]
>>> x = 'finx' + 'ter'
>>> x in set(lst)
True

The string value 'finxter‘ exists in the set {'alice', 42, 'finxter', 21, 333, None}, so the result is True.

Python Equal to NaN

To check whether a number x is equal to NaN, use the math.isnan(x) method that returns True if the number x is NaN, and False otherwise.

The following code shows an example where we first create a NaN float value using the float('nan') built-in method, and then checking that number using math.isnan(x). The result is True.

import math

x = float('nan')
print(math.isnan(x))
# True

Comparison Operators

Comparison operators are applied to comparable objects and they return a Boolean value (True or False).

OperatorNameDescriptionExample
>Greater ThanReturns True if the left operand is greater than the right operand3 > 2 == True
<Less ThanReturns True if the left operand is smaller than the right operand3 < 2 == False
==Equal ToReturns True if the left operand is the same as the right operand(3 == 2) == False
!=Not Equal ToReturns True if the left operand is not the same as the right operand(3 != 2) == True
>=Greater Than or Equal ToReturns True if the left operand is greater than or equal to the right operand(3 >= 3) == True
<=Less Than or Equal ToReturns True if the left operand is less than or equal to the right operand(3 <= 2) == False