Checking Items in a List in python
Python provides simple ways to check whether an item exists in a list using the and in operators.
not in
The in Operator
Syntax
item in list_name
Example
fruits = ["Apple", "Banana", "Orange"]
print("Apple" in fruits)
Output:
True
Since "Apple" is present in the fruits list, the result is True.
The not in Operator
Syntax
item not in list_name
Example:
fruits = ["Apple", "Banana", "Orange"]
print("Grapes" not in fruits)
Output:
True
Since "Grapes" is not present in the fruits list, the result is True.
fruits = ["Apple", "Banana", "Orange"]
print("Apple" in fruits) # True
print("Grapes" in fruits) # False
print("Apple" not in fruits) # False
print("Grapes" not in fruits) # True
Using in with an if Statement
inif
fruits = ["Apple", "Banana", "Orange"]
if "Apple" in fruits:
print("Apple is available.")
Ouput:
Apple is available.