The is keyword is an identity operator used to check whether two variables refer to the same object in memory. It returns True if both variables point to the same object; otherwise, it returns False.
a = [1, 2, 3]
b = a
print(a is b)
Output
True
Explanation: Both a and b refer to the same list object in memory. Therefore, a is b returns True.
Syntax
The general syntax of the is keyword is shown below.
object1 is object2
Or, it can be used inside an if statement as follows:
if object1 is object2:
# code
Explanation: is keyword returns True only when both variables refer to the same object in memory. If they refer to different objects, it returns False, even if the objects contain the same values.
Comparing Two Lists
The is keyword checks whether two variables refer to the same object, while the == operator checks whether their values are equal.
x = ["a", "b", "c", "d"]
y = ["a", "b", "c", "d"]
print(x is y)
print(x == y)
Output
False True
Explanation: lists x and y contain the same elements, so x == y returns True. However, they are two different list objects in memory, so x is y returns False.
Comparing Variables that Refer to Same Object
If two variables refer to the same object, the is keyword returns True.
x = [10, 20, 30]
y = x
print(x is y)
Output
True
Explanation: variable y refers to the same list object as x. Therefore, x is y returns True.
In Conditional Statements
The is keyword can be used inside an if statement to check whether two variables refer to the same object.
x = 10
y = 10
if x is y:
print("Same object")
else:
print("Different objects")
Output
Same object
Explanation: both x and y refer to the same integer object, so the condition evaluates to True and the message is printed.
Note: Small integers are commonly reused (interned) by Python implementations, so x is y may return True here. This behavior should not be relied upon for comparing values. Use == when you want to compare values.