In this article let us learn about the “==” operator in python and learn how to make use of this operator the same way the pros do!
The first step in the journey towards mastery of any programming language is to learn about the various operators provided by that language and learn how to wield them. Python is no exception to this rule!
Even though the concepts might look simple, our brains are really good at understanding the concepts but not so good at remembering them!
The best trick to make our brains remember stuff is via active learning. By “active learning” I mean “doing”!!
So put on your coding hats, open your laptops and start experimenting and playing with the code shown in the examples as you read them!
The phrase “Practice Makes Perfect” did not survive so many centuries for no reason!
For those of you who came here just to refresh your memories, here is a cheatsheet!
Python’s “==” Operator CheatSheet
|What is “==” in Python?||Equality Comparison Operator|
|How to read “==”?||“is equal to” or “equal to”|
|Use of “==” operator||To check if 2 objects are equal in terms of value|
|“==” vs “=”||“==” is for comparison while “=” is for equality|
|How to read the code “x == y”||is x equal to y?|
What is == in python? ‘==’ is an operator which is used to compare the equality of 2 objects in Python. The objects under comparison can be strings or integers or some special user-defined class
How to read “==” ? The “==” symbol is called “is equal to” or “equal to” for short and is used in many programming languages like C, C++, Python, etc.
What is the == operator used for? The “is equal to” operator is a comparison operator used to compare 2 objects for equality.
How does the “==” operator compare with the “=” operator in Python? The single equal sign “=” is the assignment operator, and the double equal sign “==” is a comparison operator.
You may ask why the language designers used ‘==’ instead of ‘=’?, that’s because of the way the computer languages evolved, and it makes sense as the assignment operators occur more frequently in computer programs compared to equality checks!
Here is a simple example
Using ‘==’ to check if 2 integer objects are equal to each other
>>> 1 == 2 False >>> 1 == 1 True
In this session at the Python interpreter,
- 1st line says “is 1 equal to 2?” and we get False
- 3rd line says “is 1 equal to 1” and we get True
In simple words, if objects on either side of the “==” operator have the same value we get True and if they have different values we get False
If you feel you have learned everything there is to know about the “==” operator, then hold your horses! There is plenty more to learn!
I urge you to call on your “virtue of patience” for another 15mins and read on! I promise you will learn a thing or 2 as we have merely scratched the surface!
I have divided this article into 4 levels as shown below.
- Level#1: Beginner
- Level#2: Intermediate
- Level#3: Advanced
- Level#4: Expert
Hence don’t worry if you have an ‘incomplete’ sort of feeling after reading the short answer above, as this article has been handcrafted to take you through the journey of learning from beginner to pro in just about 15-20 minutes and the cheatsheet above is just to get your feet wet!
Here is a short intro to the Python Interpreter for complete beginners. If you are already familiar with the interpreter, how to launch and use it, you can safely skip this side-note!
Side Note: A Short Intro to the “Python interpreter“
The Python interpreter, simply put, is the command line prompt “>>>” you will get when you enter the “python3” command in your Linux or Mac terminal (“3” stands for Python version 3).
This way of using python is also called using the “Interactive mode of the Python Interpreter”
$ python3 Python 3.8.10 (default, Sep 28 2021, 16:10:42) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
If you are in windows, you can open up the interpreter app by opening the command prompt and by entering the following command
>python Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>
Here you can play around with any python program, one line at a time as shown below!
You can even use this environment like a calculator by typing the expression to be evaluated as shown below!
I remember the first time I played around with the interpreter, it was loads of fun! To this day, it is still my go-to calculator app!
Go ahead, play a little with the interpreter! You can always bookmark this page and come back to it later!
Alright if you are done playing around with the interpreter let us go back to the main focus of this article, which is about learning the comparison operators.
Let us start our learning journey at Level#1 with a couple of examples!
LEVEL#1 (BEGINNER): Play with the “equal to”(==) operator one line at a time in the Python Interpreter
Let us have another look at the example in the cheatsheet
Using ‘==’ to check if 2 integer objects are equal to each other
>>> 1 == 2 False >>> 1 == 1 True
As we already saw, if objects on either side of the “==” operator are the same we get True and if they are different we get False
So basically if there is any expression of the form “x == y”, the Python will check both “x” and “y” and return True if x is actually equal to y
Let us take a look at another example, this time with strings.
Example#2: Using “==” to check if 2 strings are equal to each other
Let us now try to check if 2 strings are equal to each other.
>>> str1 = "apple" >>> str2 = "banana" >>> str1 == str2 False >>> str2 = "apple" >>> str1 == str2 True
Before I explain what the code does, take a minute or 2 to understand what is going on. Open your Python interpreter and try out more examples yourself before you look at the explanation!
No great programmer has achieved greatness just by reading! So go DO some coding!
Okay, let us see what the above code does!
- we assigned the string “apple” to the variable str1 and the string “banana” to the string str2.
- In line 3 above we are checking if variables str1 and str2 are equal and as expected the python interpreter prints out False.
- In line 5 we have reassigned the variable str2 to “apple” and we are doing the same equality check once more. As expected we get True as the answer this time around!
Alright, now that we have seen some examples of how to use “==” in the python interpreter environment we have successfully completed LEVEL#1!
The time has come to use the “==” operator in actual programs!
LEVEL#2: Gain mastery by using the “==” operator in Python programs!
Take a look at the following program.
Don’t feel intimidated to read code, at first it can be tough but sooner than you realize you will be reading code like you read plain English!
ans1 = input("What kind of chocolate you like? press 1 for dark and 2 for white: ") if ans1 == "1": print("The more the cocoa, better the chocolate!") elif ans1 == "2": print("Whiter the chocolate the yummier it tastes!") else: print("Invalid input!") ans2 = input("What is you phone's theme mode? press 1 for dark-mode and 2 for light-mode: ") if ans2 == "1": print("Dark mode looks the coolest!") elif ans2 == "2": print("Light mode is simply classic!") else: print("Invalid input!")
- In the 1st 2 if statements we are simply asking the user to enter 1 or 2 and
- based on the input by the user we decide what needs to be printer.
Notice how we have made use of the “==” operator to make the checks!
SideNote: Prepare for Random inputs!
On a side note see how each of the 1st 2 if statements have 3 parts: if, elif, and else. While programming in any language, we must always be prepared for any random input from the user! In other words, don’t expect the user to always act sane and be ready for some insane inputs like shown below!
What kind of chocolate you like: press 1 for dark and 2 for white: I like caramel! Invalid input!
Congratulations! You have successfully completed Level#2!!
LEVEL#3 (ADVANCED): Compare Multiple variables/values in One-Go!
Let us kick things up a notch and learn how we can compare more than 2 values using the “==” operator in one go!
Chaining “==” Operators
Let us extend Example#3 with a few more lines.
ans1 = input("What kind of chocolate you like? press 1 for dark and 2 for white: ") if ans1 == "1": print("The more the cocoa, better the chocolate!") elif ans1 == "2": print("Whiter the chocolate the yummier it tastes!") else: print("Invalid input!") ans2 = input("What is you phone's theme mode? press 1 for dark-mode and 2 for light-mode: ") if ans2 == "1": print("Dark mode looks the coolest!") elif ans2 == "2": print("Light mode is simply classic!") else: print("Invalid input!") # You can also use "==" operator in a chained fashion as shown in the example below if ans1 == ans2 == "1": print("You have a cool personality!") elif ans1 == ans2 == "2": print("You have a bright personality!") else: print("You have a dynamic personality!")
The 3rd part of the program (starting from line 17) is more interesting, here we are chaining 2 “==” operators to compare 3 objects for equality in one line!
Internally, to achieve the comparison of 3 objects, Python will do the following steps
- take the 1st and 2nd objects and compare them for equality
- take the 2nd and 3rd objects and compare them for equality
- if both comparisons turns out to be True, then return True
- if even one comparison turns out to be False, then return False
The above steps can be represented via pseudocode as shown below.
if (object1 == object3) AND (object2 == object3) return TRUE
So in our program in Example#3 above, the interpreter translates the chained “==” operations and translates them into something like shown below before executing the code
if (ans1 == "1") AND (ans2 == "1"): print("You have a cool personality!") elif (ans1 == "2") AND (ans2 == "2"): print("You have a bright personality!") else: print("You have a dynamic personality!")
I hope that by now you understand how chaining the “==” operator works internally.
LEVEL#4 (EXPERT): Become a Pro and gain full control of the “==” operator and make it dance to your will!
Bravo if you have made it this far to Level#4! You really have a hunger for knowledge! Keep it up and you will become an expert python programmer very soon!
Time for us to take things to the highest possible level and learn how python implements the “==” operator internally and see how we can modify this behavior to make Python dance to our wills!
How ‘==’ is implemented in Python
Before starting to learn how “==” is implemented inside Python, let us first learn a little bit about objects and methods in Python.
In Python all everything like integers, strings, lists, etc are Objects and all objects have some methods you can call to do some cool things with them. A good analogy would be
“methods” are like “dance moves” which a particular dancer (a given object) can do!
For example, consider the simple example below.
>>> string1 = "Hello Inventor!" >>> string1.swapcase() 'hELLO iNVENTOR!' >>>
Here the swapcase() method is used to make all uppercase letters into lowercase and vice versa!
If you wish to know what methods the string objects support, you can type the following command into the python interpreter.
You will get something like this
The screenshot below shows the usage of the help() command with the str type object
If you scroll a bit yourself, you will find yourself looking at a method named eq() as shown in the screenshot below.
This method is available for all built-in types like string, int, list, set, etc.
Let us experiment with how __eq__() behaves with integers.
>>> a = 20 >>> b = 10 + 10 >>> a.__eq__(b) True
As you can see from the example above, this method takes another object as an argument (the variable b in our case) and compares both of them for equality, which is the exact same thing our “==” operator does!
So in essence, whenever we use the operator “==” in our code, Python translates that to the form as shown above before executing the code!
a == b Becomes a.eq(b)
You might be thinking at this point “But what is the use of learning this detail?“
Say you have your own class, which you wish to give to your friends, and you have your own logic of comparing 2 objects of the class you defined yourself for equality. Then if you want the “==” operator to work on your class, you need to implement the eq() method in your own class.
Let us see how to do that in the next section!
What is the default behavior of “==” operator
According to python documentation
By default, object implements eq() by using is, returning NotImplemented in the case of a false comparison: True if x is y else NotImplemented.https://docs.python.org/3/reference/datamodel.html
Do not worry if the above line does not make any sense to you. In essence, what the above statement says is by default
If the 2 names are just different names for the same object we get True, if they are pointing to different objects we get False
Alright, too much theory! Time for an example!
Let us see a simple fruit class as shown below.
class fruit(): def __init__(self, name, price_kg): self.name = name self.price_kg = price_kg
The above class has 2 attributes “name” and “price_kg” and a constructor init() to set these attributes.
Let us play with this fruit class by creating some objects on the Python interpreter
>>> apple = fruit("apple",10) >>> mango = fruit("mango",20) >>> pear = fruit("pear",10) >>> apple == mango False >>> mango == pear False >>> apple == pear False
In the code above
- We have made 3 objects: apple, mango and pear
- apple and pear are priced at 10 bucks per kg and
- the mango is priced at 20 bucks per kg.
When we do some equality checks, all the comparisons between the 3 fruits above result in False.
Let us try creating another apple!
>>> apple2 = fruit("apple", 10) >>> apple == apple2 False
Even if we made another apple object with the same name and price, we still get False when we try to compare this with the 1st apple!
That is because these 2 apples are different objects stored in 2 different locations in memory!
You can verify this using the built-in id() function.
>>> id(apple) 140610421339424 >>> id(apple2) 140610392624672
Each object is given an ID number when they are created. As you can see above the objects apple and apple2 has different IDs and hence by default they are not “Equal”
Okay, so you might be wondering “Does this mean by default every equality comparison will result in False?“
Let us try to compare apple2 with apple2!
>>> apple2 == apple2 True
Yaay! We got a True at last!
But wait for a second, why in the world would we wish to do something like this in our programs anyways!
Okay, that is a valid confusion!
In Python, we are allowed to have 2 names for the same object. This is something like a nickname and an official name for the same person.
Since these 2 names refer to the same person, the “names of objects” are also called “references“
Let us see what I mean
>>> apple2_copy = apple2 >>> id(apple2) 140610392624672 >>> id(apple2_copy) 140610392624672 >>> apple2_copy == apple2 True
Here I have created a copy of “apple2” called “apple2_copy“. In essence, now we now have 2 names for the same object with id 140610392624672
Now if we do an equality comparison, we get True!
So by default the “==” operator sees if the 2 names being compared are referring to the same object or not!
So the default behavior is
if the 2 names are just different names for the same object we get True, if they are pointing to different objects we get False
I hope now you get the meaning behind the lines above and you understand the default behavior of the equality operator perfectly!
Need to change the default behavior of ‘==’ in user defined classes
Assume we are fruit sellers. When comparing 2 fruits, the only thing fruit sellers are interested in is the parameter “price per kg“.
Let us expand the fruit class by including the eq() method as shown below.
class fruit(): def __init__(self, name, price_kg): self.name = name self.price_kg = price_kg def __eq__(self, b): return (self.price_kg == b.price_kg)
Now, the fruit class still has the same 2 attributes “name” and “price_kg“. But we have 2 methods, the constructor init() and eq() method to implement the behavior of the fruit class
Let us play with this fruit class now in the python interpreter!
>>> peach = fruit("peach", 10) >>> kiwi = fruit("kiwi", 20) >>> mango = fruit("mango", 20) >>> peach == kiwi False >>> kiwi == mango True
As you can see this time, the “==” operator compares the objects using the price!
- Peach and Kiwi has different prices and we get False, while
- Kiwi and mango has the same price and hence we get “True“!
Let us take one more example. Let us take the same fruit class but this time assume we have a shipping business, where we put fruits into crates and ship them.
In this kind of shipping business, we need to know how many fruits can go into one of our crates. Hence we need the size and weight of a given fruit to decide if they are equal or not.
class fruit(): def __init__(self, name, diameter, weight): self.name = name self.diameter = diameter self.weight = weight def __eq__(self, b): return (self.diameter == b.diameter) and (self.weight == b.weight)
Here we have a class named fruit. Each fruit comes with 3 attributes (name, weight, and diameter).
We have the same 2 methods, the constructor init() and the eq() class which we need to use to compare the fruits for packaging and shipping purposes.
Let us take our new fruit class for a spin!
>>> apple = fruit("apple", 10, 200) >>> wmelon = fruit("watermelon", 50, 5000) >>> orange = fruit("orange", 10, 200) >>> apple == wmelon False >>> apple == orange True
As you can see
- the comparison between apple and watermelon gives us a “False”
- but the comparison between apple and orange gives us a “True“
That is because, in our class, the eq() operator returns True if the diameter and weight are both equal!
So even though they are not the same fruit, we call them equal as the parameters we care about (the weight and the diameter) are equal. Hence we made the “==” operator behave exactly the way we wanted it to!
I hope you understood how to define the behavior of the “==” operator for your own classes!
If you did then bravo! You have successfully mastered the “==” operator in Python!
There are some more operators in python which act very similar to the “==” operator in terms of implementation and usage. Since you have already learned everything there is to know about the “==” operator, you already know everything to know about some more operators too!
These are the 5 other comparison operators like our “==” operator:
- > : Greater than
- >= : Greater than or Equal to
- < : Less than
- <= : Less than or Equal to
- != : Not Equal to
All these operators are implemented and used very similar to the way we use the “==” operator. We have written a separate article explaining each of them using examples, please check them out in the link below!
Another common confusion among beginner Python programmers is the difference between the “==” and “is” operators.
“==” vs “is” in python
What does the “is” operator do in Python?
The “is” operator in Python is used to check if 2 references are pointing to the same object or not.
If the term “references” and “objects” does not sound very familiar to you, please read our article explaining the “is” operator in great detail, which you can find in the link below.
There I have explained in detail
- the meaning of “references”,
- how the “is” operator works and
- how and when to use “is” operator as compared to the “==” operator.
Where to Go from Here
I suggest first playing a bit more with the “==” operator just to get some practice. Once you are done, the next obvious step would be to go and master the other operators!
You can find the articles in the related articles section below.
If you have made it till the end, then congratulations and keep up this habit of finishing what you start, that is the one habit that differentiates winners from losers, and you have proved yourself to be a winner!
I hope you had some fun reading this article and you learned something useful!
Feel free to share this article with your friends and colleagues!
Here are some of the other articles on our website that you might find interesting!