πŸ”Ž 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 πŸ“‹

OperatorMeaningExample
inTrue if the value is present in the sequencex in y
not inTrue if the value is NOT presentx 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)     # False

Note

βœ”οΈ 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)   # True

4. Membership With Tuples πŸ”—

tuple_membership.py

colors = ("red", "green", "blue")

print("green" in colors)    # True
print("yellow" not in colors) # True

5. 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)     # True

6. 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())  # True

Note

πŸ’‘ 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! 😊