π Python Membership Operators β Checking Presence in Sequences
Introduction π
Membership operators allow you to check whether a value exists inside a sequence such as a string, list, tuple, set, or dictionary. They return True or False and are commonly used in conditions, loops, and searches.
Note
π‘ Membership operators make your code cleaner by avoiding manual loops to check values.
1. List of Membership Operators π
| Operator | Meaning | Example |
|---|---|---|
| in | True if the value is present in the sequence | x in y |
| not in | True if the value is NOT present | x not in y |
2. Membership With Strings π€
string_membership.py
text = "Python Programming"
print("Python" in text) # True
print("Java" in text) # False
print("ing" in text) # True
print("Py" not in text) # FalseNote
βοΈ String membership checks for substrings β not whole words only.
3. Membership With Lists π¦
list_membership.py
numbers = [10, 20, 30, 40]
print(20 in numbers) # True
print(25 in numbers) # False
print(50 not in numbers) # True4. Membership With Tuples π
tuple_membership.py
colors = ("red", "green", "blue")
print("green" in colors) # True
print("yellow" not in colors) # True5. Membership With Sets π―
Sets check membership very fast due to hashing.
set_membership.py
ids = {101, 102, 103}
print(102 in ids) # True
print(200 not in ids) # True6. Membership With Dictionaries ποΈ
Membership checks keys only β not values β unless explicitly checked.
dict_membership.py
student = {"name": "Sathish", "age": 25, "city": "Chennai"}
print("name" in student) # True (key check)
print("Sathish" in student) # False (value is not a key)
# To check values:
print("Sathish" in student.values()) # TrueNote
π‘ Use .keys(), .values(), or .items() for specific membership checks.
7. Membership in Conditions π§
condition_membership.py
allowed_users = ["admin", "manager", "superuser"]
username = input("Enter username: ")
if username in allowed_users:
print("Access granted")
else:
print("Access denied")8. Combining Membership With Logical Operators π
combined_membership.py
word = "python"
if ("p" in word) and ("z" not in word):
print("Valid word")9. Real-World Example π
real_world_example.py
email = input("Enter your email: ")
if "@" in email and "." in email:
print("Valid email format")
else:
print("Invalid email")Conclusion π
>>βMembership operators let your program search intelligently β simple, fast, and powerful.β β¨
You now understand Python membership operators! Want the next topic? Try Conditional Statements, If-Else, Nested Conditions, Loops, or Control Flow. Just tell me! π