Python IS Operator - Example Programs
Python is keyword is used to check if the memory reference of two Python objects are same or not.
Python is operator takes two operands and returns True if both the objects have same memory reference and False if not.
Example 1: Python IS Operators
In the following example, we will demonstrate the usage and functioning of Python is operator.
Python Program
a = [5, 8]
b = [5, 8]
c = a
if a is b:
print('a is b')
else:
print('a is not b')
if a is c:
print('a is c')
else:
print('a is not c')
Output
a is not b
a is c
Explanation
- Condition 1:
a is b
- The contents of a and b are the same, but a and b are different objects with different memory references. So,
a is b
evaluates to False, anda is not b
evaluates to True. - Condition 2:
a is c
- Here, a is assigned to c, meaning both variables refer to the same memory location. Therefore,
a is c
evaluates to True, anda is not c
evaluates to False.
Example 2: Python IS with Immutable Objects
In this example, we demonstrate how the is operator behaves with immutable objects like integers and strings.
Python Program
x = 256
y = 256
z = 1000
w = 1000
if x is y:
print('x is y')
else:
print('x is not y')
if z is w:
print('z is w')
else:
print('z is not w')
Explanation
- Condition 1:
x is y
- For small integers (from -5 to 256), Python caches the objects, so x and y refer to the same memory location. Hence,
x is y
evaluates to True. - Condition 2:
z is w
z is w
evaluates to True.
Output
x is y
z is w
Example 3: Python IS with Strings
Here, we demonstrate the is operator with strings to highlight memory reference comparison.
Python Program
str1 = 'hello'
str2 = 'hello'
str3 = ''.join(['h', 'e', 'l', 'l', 'o'])
if str1 is str2:
print('str1 is str2')
else:
print('str1 is not str2')
if str1 is str3:
print('str1 is str3')
else:
print('str1 is not str3')
Explanation
- Condition 1:
str1 is str2
- In Python, small strings are interned, meaning they are stored at a single memory location. Hence, both str1 and str2 refer to the same memory location, and
str1 is str2
evaluates to True. - Condition 2:
str1 is str3
- The str3 is created using the
join()
method, and although its value is the same as str1, it is not interned. Therefore,str1 is str3
evaluates to False.
Output
str1 is str2
str1 is not str3
Summary
In this tutorial of Python Examples, we learned how to use the is keyword in Python to compare the memory reference of two objects, with the help of example programs.