/  Technology   /  Comparing string uses either ‘==’ or ‘is’ ?

Comparing string uses either ‘==’ or ‘is’ ?

Why does comparing strings using either ‘==’ or ‘is’ sometimes produce a different result?

 

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 

True

 >>> a is b 

False

 

 

Leave a comment