/  Technology   /  Comparing string uses either ‘==’ or ‘is’ in Python
comparing strings

Comparing string uses either ‘==’ or ‘is’ in Python


The “is” operator  is used for identity comparison, whereas the  “==” operator is used for equality comparison.


Let us try to understand this with a real life example. There’s a person named Harry who’s 23 years old.Now he is equivalent to another person also named Harry  and is also 23 years old.Though they share the same name and age,in actual existence, both the persons are not the same.


Now speaking technically, ‘is’ compares the memory addresses to see if the values refer to the same object or not. Python optimizes the memory usage and will often refer multiple variable names with the same value to the same location; this optimization can vary from execution of a script to the use of it in the terminal.


Because of this reason we generally don’t use the ‘is’ operator to compare the value of objects. Whereas the  “=”operator on the other hand compares the value rather than the ids of two objects.

>>> a = ‘python’ 
>>> b = ‘ ‘.join([‘p’, ‘y’, ‘t’, h’, ’o’, ’n’])
 >>> a == b 
 >>> a is b 



Comparing Strings


Leave a comment