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
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
Check if a given string is binary string or not - Python
The task of checking whether a given string is a binary string in Python involves verifying that the string contains only the characters '0' and '1'. A binary string is one that is composed solely of these two digits and no other characters are allowed. For example, the string "101010" is a valid bi
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
Convert Strings to Numbers and Numbers to Strings in Python
Converting strings to numbers and numbers to strings is a common task in Python. In this article, weâll explore simple ways to convert between strings and numbers .Using int() and str()int() and str() functions in Python are commonly used for converting data types. The int() function changes a strin
3 min read
Difference between Sums of Odd and Even Digits in Python
Write a python program for a given long integer, we need to find if the difference between sum of odd digits and sum of even digits is 0 or not. The indexes start from zero (0 index is for the leftmost digit). Examples: Input: 1212112Output: YesExplanation:the odd position element is 2+2+1=5the even
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
Return True if Cast Between Data Types can Occur According to the Casting rule in Python
In this article, we will see that if the program returns True if the case between different data types can occur according to the casting rule of Python. Casting Rules in Python In Python, the term "casting" refers to the method of converting one datatype into another. In Python, there are certain b
5 min read