Python IS NOT Operator - Example Programs


Python IS NOT

Python is not operation is simply the opposite of Python is.

Python is not checks if the two operands refer to the same memory reference. If they do not have the same memory reference, python is not returns True, else it returns False.


Example 1: Python IS NOT Operator

In the following example, we will use is not operator in the Python If statement.

Python Program

a = [5, 8]
b = [5, 8]
c = a

if a is not b:
	print('a is not b')
else:
	print('a is b')

if a is not c:
	print('a is not c')
else:
	print('a is c')

Explanation

  1. The contents of a and b are the same, but a and b are different objects that occupy different memory locations.
  2. In the condition a is not b, Python compares the memory references of a and b. Since their memory locations are different, the condition evaluates to True, so the statement a is not b prints a is not b.
  3. When a is assigned to c, it copies the reference to the same memory location, not the actual contents. Therefore, a and c point to the same list.
  4. The condition a is not c evaluates to False because both a and c share the same memory reference. So the statement a is c prints a is c.

Output

a is not b
a is c

Example 2: Python IS NOT with Immutable Objects

In this example, we will use the is not operator to compare immutable objects.

Python Program

a = 10
b = 10

if a is not b:
	print('a is not b')
else:
	print('a is b')

Explanation

  1. Here, a and b are both assigned the same value of 10 (an immutable integer).
  2. In Python, small integers are cached and stored at the same memory reference. So, even though a and b are different variables, they will refer to the same memory location.
  3. The condition a is not b evaluates to False, as both a and b share the same memory reference for the integer 10.
  4. The output is a is b.

Output

a is b

Summary

In this tutorial of Python Examples, we learned how to use the is not operator in Python. The is not operator is used to compare the memory references of two objects and returns True if they are not the same. We covered examples of comparing lists, strings, integers, and other data types with the is not operator.


Python Libraries