Relation between Equality(= =) and Identity (is) operators

Preview

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: ‘)
Enter your name: lovejot

In[3]:  str1==str2
Out[3]: True

In[4]: str1 is str2
Out[4]: False

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
Out[3]: True

 In[4]:  value1 is value2
Out[4]: False

In[5]:  id(value1),id(value2)
Out[5]: (164643136, 189130944)

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
Out[3]: True

In[4]:  var1 is var2
Out[4]: False

In[5]:  id(var1),id(var2)
Out[5]: (198464336, 198464464)

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
Out[3]: True

In[4]:  var1 is var2
Out[4]: False

In[5]:  id(var1),id(var2)
Out[5]: (198467056, 198465040)

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.

Lesson tags: difference in equality and identity operator, equality operator in python, is operator in python
Back to: Python Programming Tutorial