Relation between Equality(= =) and Identity (is) operators
We have seen that if values of two variables are same,
a=10
b=10
a==b and a is b
will return true
But it is not always true.
There are some cases where two variables have same value but they return different results. It happens because there are few cases where Python creates two different objects having same value .These cases are:
- Reading a string value
- Complex values
- Floating point values
- Long integer values
1. Reading a string
When we read a string value, it is always assigned a different id.
In[1]: str1=’lovejot’ In[2]: str2=input(‘Enter your name: ‘) In[3]: str1==str2 In[4]: str1 is str2 |
Note: In above Python statements we can see that str1 and str2 contain same value but str1 is str2 returns false because Python allocated different ids to variables str1 and str2
2. Complex Values
Complex values are always assigned different ids even for same values.
In[1]: value1=2+5j In[2]: value2=2+5j In[3]: value1 == value2 In[4]: value1 is value2 In[5]: id(value1),id(value2) |
Note: In above Python statements we can see that variables value1 and value 2 contain same value but value1 is value2 returns false because Python allocated different ids to variables value1 and value2.
3. Floating point Values
Floating point values are always assigned different ids even for same values.
In[1]: var1=2.5 In[2]: var2=2.5 In[3]: var1 == var2 In[4]: var1 is var2 In[5]: id(var1),id(var2) |
Note: In above Python statements we can see that variables var1 and var 2 contain same value but var1 is var2 returns false because Python allocated different ids to variables val1 and val2.
4. Very big integer Values
Small integer values are assigned same id by Python but long integer values are always assigned different ids even for same values.
In[1]: var1=99999 In[2]: var2=99999 In[3]: var1 == var2 In[4]: var1 is var2 In[5]: id(var1),id(var2) |
Note: In above Python statements we can see that variables var1 and var 2 contain same value but var1 is var2 returns false because Python allocated different ids to variables val1 and val2.