Python  is keyword  == operator  
   Technology    Programming

Difference between is and == in Python

 JUNE 11, 2019   by hafeezulkareem

In this tutorial, we are going to see the difference between is and == in Python. Now, most of you must have used is and == in python for comparing variables and hence must be wondering that how can they be different, right. So let's see the usage of both is and == operator with examples to understand the difference between them.

is keyword vs == operator in python

is Keyword

is is a keyword in python which is used to check whether two objects are exactly the same or not? For instance, we have a variable first with integer value 2 and another variable second with the same value 2.

When we use the is operator to check whether they are similar or not, we get the result as True, which means they are the same. In python, variables with equal values are assigned the same id for their objects to save the memory. So, the statement a is b is True. Below we have a code sample, run it to see the output:

a = 2
b = 2
print(a is b)

Output of the code:


Now this is only valid for the variables with some value assigned. Let's take another example, consider that we have two empty lists list1 = [] and list2 = []. Two different lists in python refer two different objects with two different memory locations. So, list1 and list2 are not exactly similar. See the example below:

list1 = []
list2 = []
print(list1 is list2)

Output of the code:


As you can see in the output above, we are getting different values for both the list variables even though both are empty which means that their values are equal, but still, they are not the same, hence the result is false.

== Operator

== is a comparison operator in python. It is used to compare two objects/variables to find out whether the objects/variables are equal or not. It is called the equality operator. If we take the above example where we had two empty lists, and compare them using the == operator, we will get True as the result. Below we have a simple code example:

list1= []
list2 = []
print(list1 == list2)

Output of the code:


The == operator returns true when the values are equal. It doesn't compare or worry about the object id.

Difference between is and ==

The keyword is checks whether the variables are referring to the same object or not. If they are referring to the same object, then they have the same id otherwise they will have different id's.

Whereas, the == operator compares the values while checking whether they are referring to the same object or not.

If this article helped you in understanding the difference between is keyword and == operator in python, share it with your friends and colleagues, bookmark it and share in comments what topic you would like us to cover in Python programming language.