Membership Operators
Membership operators are used to check if a value exists inside a sequence (like a sentence of text or a list of items).
Think of it as searching for something inside a container.
Python has two membership keywords: in and not in.
1. The in Operator
Returns True if the value is found inside the container.
Searching inside text (Strings):
sentence = "Python is the future of AI"
# Check if the word "AI" is inside the sentence
print("AI" in sentence) # Output: True
print("Java" in sentence) # Output: False
Searching inside lists:
# A list of names (we will learn more about lists later!)
names = ["Rahul", "Sai", "Priya"]
print("Sai" in names) # Output: True
print("John" in names) # Output: False
2. The not in Operator
Returns True if the value is not found inside the container (returns the opposite of in).
sentence = "Python is the future of AI"
print("Java" not in sentence) # Output: True (Java is indeed not there!)
print("AI" not in sentence) # Output: False (Because AI is there!)
Quick Summary
inOperator: Checks if an element exists inside a collection (string, list, tuple, etc.) and returnsTrueif found.not inOperator: Checks if an element is absent from a collection and returnsTrueif missing.- Membership in Strings: Searches sub-strings within larger text (e.g.,
"AI" in "Python for AI"->True).
What's Next?
Congratulations on completing Module 4! Now that we know all the operators, let's learn how to make smart decisions in code using Conditional Statements (if, elif, else) in Module 5!