Table of Contents
Introduction
The equals (==) operator and is operator of python are the check operators. The equals (==) operators checks whether the values of objects are same or not, whereas the is operators checks whether the object points to the object of the same memory location.
Sample code to get the id of objects:
sample_list1 = [] sample_list2 = [] print(id(sample_list1)) print(id(sample_list2))
140214539034112
140214538406144
The id() function returns the unique id of the object that is assigned when the object is created. From the above code, we can see that sample_list1 and sample_list2 refer to two different objects.
Syntax
Equals: If ( var1 == var2 )
Is: If (var1 is var2)
Program
sample_list1 = [] sample_list2 = [] sample_list3 = sample_list1 sample_list4 = sample_list1 + sample_list2 if (sample_list1 == sample_list2): print("True") else: print("False") if (sample_list1 is sample_list2): print("True") else: print("False") if (sample_list3 is sample_list1): print("True") else: print("False") if (sample_list3 is sample_list4): print("True") else: print("False")
Output
True
False
True
Falsex
Explanation
In the first case, we are checking the variables whether they are equal or not. The smaple_list1 and sample_list2 are two empty lists, and thus is satisfies the equal’s condition. Therefore, the output is True.
In the second case, we are checking the two variables whether they point to the same object or not. The variable smaple_list1 and sample_list2 are two different objects pointing to different memory locations. Therefore, the output is False.
In the third case, we have assigned the value of sample_list1 to variable smaple_list3 and checked whether they point to the object at the same memory location. The output is True as both the variables share the same memory location.
In the fourth case, we have checked whether the variable sample_list3 and sample_list4 points to the same memory location or not. The two objects are different and therefore the output is False.
0 Comments