search

What is the use of the "not in" keyword in Python?

The "not in" keyword in Python is used to test if an item does not exist in a sequence (such as a list, tuple, set, or string). The keyword returns **True** if the item is not present in the sequence, and **False** otherwise.

For example:

# Checking if an item does not exist in a list
fruits = ['apple', 'banana', 'cherry']
if 'grapes' not in fruits:
    print("Grapes are not in the list")
else:
    print("Grapes are in the list")

# Checking if an item does not exist in a string
name = "John Doe"
if 'Jane' not in name:
    print("Jane is not in the name")
else:
    print("Jane is in the name")

The "not in" keyword can also be used to check if a key does not exist in a dictionary:

# Checking if a key does not exist in a dictionary
person = {'name': 'John Doe', 'age': 30}
if 'address' not in person:
    print("Address key does not exist in the dictionary")
else:
    print("Address key exists in the dictionary")

Related Questions You Might Be Interested