The in operator is used to check whether a given element exists in a sequence (such as a list, tuple, string, or dictionary).
It returns True if the element exists, and False otherwise.
Example 1: Using in with Lists
Visual Representation
sample_list = [3, 6, 9, 12, 15]
print(3 in sample_list)
print(5 in sample_list)
Output
True
False
Example 2: Using in with Strings
Visual Representation
text = "Hey, CR7!"
print("CR7" in text)
print("Hello" in text)
Output
True
False
Example 3: Using in with Dictionaries
In dictionaries, in checks for the presence of a key.
Visual Representation
sample_dict = {"a": 1, "b": 2, "c": 3}
print("c" in sample_dict)
print("x" in sample_dict)
Output
True
False
Example 4: Using in with Conditional Statements
# Define a tuple
sample_tuple = (10, 20, 30, 40, 50)
# Check if an element exists in the tuple
if 20 in sample_tuple:
print("20 is in the tuple.")
else:
print("20 is not in the tuple.")
# Check for another element
if 80 in sample_tuple:
print("80 is in the tuple.")
else:
print("80 is not in the tuple.")
Output
20 is in the tuple.
80 is not in the tuple.