Editor settings

General settings

Save settings

Learn to program with Python

Identity comparison with is keyword #

The is keyword is used for object identity comparison. Whenever we create a value in Python, we created an object that is stored in the memory, and the keyword is checks if two objects are the same object by comparing their memory locations, whereas the == operator compares the values of the objects.

For example:

a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)  # True
print(a is b)  # False

print(a == c)  # True
print(a is c)  # True

In the above example, a and b have the same values but they point to different memory locations because they were created separately, so a is b returns False. On the other hand, a and c both point to the same memory location, so a is c returns True.

It's important to note that is keyword should be used only for comparing with None, and sometimes True and False if you want to check if the value is the True or False objects. For example:

a = True
b = 50

print(b == True) # True
print(b is True) # False
print(a is True) # True

There are cases where is can be useful for comparing object identities. For instance, when we want to check if a variable has been assigned any value, we can use is None instead of == None. Here is an example:

my_var = None

if my_var is None:
    print("my_var has no value")
else:
    print("my_var has a value")

Exercise #

Fix the code inside the function is_true_or_false() to check if the variable value is really a boolean True or False.

Tests #

  • is_true_or_false(True) should return True
  • is_true_or_false(False) should return True
  • is_true_or_false(None) should return False
  • is_true_or_false(1) should return False
  • is_true_or_false(0) should return False
  • is_true_or_false([1, 2, 3]) should return False
  • is_true_or_false([]) should return False
Output will be displayed here