Why does comparing strings using either ‘==’ or ‘is’ sometimes produce a different result in Python?
Last Updated :
09 Jan, 2023
Python offers many ways of checking relations between two objects. Unlike some high-level languages, such as C++, Java, etc., which strictly use conditional operators. The most popular operators for checking equivalence between two operands are the == operator and the is operator. But there exists a difference between the two operators. In this article, you will learn why comparing strings using ‘==’ or ‘is’ sometimes produces different results in Python.
What is the ‘is’ operator?
is is an identity operator in Python. That is used to check if two values (or variables) are located on the same part of the memory. Two equal variables do not imply that they are identical. i.e., The operators compare the id of both the operands, and if they are the same, then the output is true otherwise false. An example to demonstrate the use case of is operator is:
Python3
a = "apples"
b = "apples"
c = "". join([ 'a' , 'p' , 'p' , 'l' , 'e' , 's' ])
print (a is b)
print (a is c)
|
Output:
True
False
Firstly two variables were initialized with the same string (interning). Then a list containing the same alphabet as the string mentioned earlier was defined and joined using the join function. Then a and b are checked for identity equivalence, and a and c are also checked for identity equivalence. The former results in True as both the strings are simultaneously existing objects. Python only created one string object, and both a and b refer to it. The reason is that Python internally caches and reuses some strings as an optimization. The latter results in a False even though the contents of either string are the same. This is because the c string was created by joining a list. Due to this, the list was the initial object whose id did not equal that of the string. Therefore, even though the contents of the strings are the same, the result is False.
What is the ‘==’ operator?
== is a conditional/relational operator used to check whether the operands are identical. The operator considers the data stored by the operands to check their equality. An example to demonstrate the use case of the == operator is:
Python3
a = "apples"
b = "apples"
c = "". join([ 'a' , 'p' , 'p' , 'l' , 'e' , 's' ])
print (a = = b)
print (a = = c)
|
Output:
True
True
The same code as the previous one was used, this time with the == operator for checking. Both the checks evaluated to True result. This is because the operator checks the contents of the operands for comparison, which are the same in both cases. Therefore, it is advised to use the == operator over is operator if wanting to check whether the operands are equivalent.
When to use the ‘is’ operator and when to use the == operator?
Both operators, even though offering similar functionality, should be used for completely different purposes. The is operator checks whether the two operands are identical or not. By identical, it means whether the two objects are the same. It does so by checking the id of both objects, and if the id is the same, then the objects are true (not in the case of numbers). Comparison of integers and strings (for equality) should never be done using the operator. Comparisons to singletons like None should be done using the operator.
Hence, the is operator should be used to check identity, not equivalence.
The == operator is used to check the equivalence between the operands. The operator does not require the operands to be identical. The operator should be used to check the equality between integers and strings.
Hence, the == operator should be used to check equivalence, not identity.
Similar Reads
Different Ways of Using Inline if (ternary operator) in Python
Python offers a simple and concise way to handle conditional logic by using inline if, also known as the ternary operator or conditional expression. Instead of writing a full if-else block, we can evaluate conditions and assign values in a single line, making your code cleaner and easier to read for
4 min read
Compare sequences in Python using dfflib module
The dfflib Python module includes various features to evaluate the comparison of sequences, it can be used to compare files, and it can create information about file variations in different formats, including HTML and context and unified diffs. It contains various classes to perform various comparis
5 min read
Using Else Conditional Statement With For loop in Python
Using else conditional statement with for loop in python In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while
2 min read
Compare Strings for equality or lexicographical order in different programming Languages
Given two strings string1 and string2, the task is to check if these two strings are equal or not. Examples: Input: string1 = âGeeksforGeeksâ, string2 = âGeeksforGeeksâ Output: Yes Input: string1 = âGeeks for Geeksâ, string2 = âGeeks for Geeksâ Output: Yes Input: string1 = âGeeksforGeeksâ, string2 =
8 min read
Check if both halves of the string have same set of characters in Python
Given a string of lowercase characters only, the task is to check if it is possible to split a string from middle which will gives two halves having the same characters and same frequency of each character. If the length of the given string is ODD then ignore the middle element and check for the res
3 min read
Test whether the elements of a given NumPy array is zero or not in Python
In numpy, we can check that whether none of the elements of given array is zero or not with the help of numpy.all() function. In this function pass an array as parameter. If any of one element of the passed array is zero then it returns False otherwise it returns True boolean value. Syntax: numpy.al
2 min read
How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
Equal Operator == The comparison operator called Equal Operator is the double equal sign "==". This operator accepts two inputs to compare and returns true value if both of the values are same (It compares only value of variable, not data types) and return a false value if both of the values are not
2 min read
Return a boolean array which is True where the string element in array ends with suffix in Python
In this article, we are going to see how we will return a boolean array which is True where the string element in the array ends with a suffix in Python. numpy.char.endswith() numpy.char.endswith() return True if the elements end with the given substring otherwise it will return False. Syntax : np.c
2 min read
How to check if a string is a valid keyword in Python?
In programming, a keyword is a "reserved word" by the language that conveys special meaning to the interpreter. It may be a command or a parameter. Keywords cannot be used as a variable name in the program snippet. What is Keywords in PythonPython also reserves some keywords that convey special mean
2 min read
How to Compare List of Dictionaries in Python
Comparing a list of dictionaries in Python involves checking if the dictionaries in the list are equal, either entirely or based on specific key-value pairs. This process helps to identify if two lists of dictionaries are identical or have any differences. The simplest approach to compare two lists
3 min read