in keyword with sets in Python
in / not in Keyword in Python The in keyword is used to check whether an element exists in a set (or any iterable such as a list, tuple, or string).
Syntax
element in set_name
element not in set_name
Return Value
- Returns True → if the element exists in the set.
- Returns False → if the element does not exist in the set.
Example: Basic Usage
Python
# Define a set
fruits = {"apple", "banana", "cherry"}
print("apple" in fruits) # True
print("grape" in fruits) # False
print("banana" not in fruits) # False Explanation
- "apple" exists in the set → True
- "grape" does not exist in the set → False
- "banana" not in fruits → False because "banana" is present
Example: Using in Inside if Statement
Python
# Define a set
colors = {"red", "green", "blue"}
if "green" in colors:
print("Green is available!")
else:
print("Green is not available.") Output Green is available!
Example: Case Sensitivity
Python
# Define a set
animals = {"Cat", "Dog", "Elephant"}
print("cat" in animals) # False
print("Cat" in animals) # True Note: Sets are case-sensitive, just like strings. "Cat" and "cat" are treated as different values.