What are Membership Operators ?
Membership operators are keywords used in Python to test whether a specific value or sequence is present inside a collection.
Unlike standard arithmetic or comparison operators, membership operators are designed to search through sequential data structures—such as Strings, Lists, Tuples, Sets, and Dictionaries. When you run a membership check, Python scans the targeted data container and returns a Boolean value: either True if the item is found, or False if it is absent. These keywords make it exceptionally easy to validate user inputs or search for terms without writing manual loops.
Python Membership Operators Table
Assuming we are searching for data inside a list variable: fruits = ["apple", "banana", "mango"]
| Operator | Name | Syntax |
|---|---|---|
| in | In | "mango" in fruits |
| not in | Not In | "grape" not in fruits |
1. The in Operator
The in operator evaluates to True if it finds the specified element inside the target sequence. If the collection does not contain that exact value, it returns False.
# A list of blacklisted email domains blocked by a system
blocked_domains = ["spammail.com", "fakeaccount.net", "trashbin.org"]
# A new user attempts to register with this email
user_email = "user@fakeaccount.net"
# Splitting the email to isolate the domain part
user_domain = "fakeaccount.net"
# Using 'in' to verify if the domain is on the blacklist
is_blocked = user_domain in blocked_domains
print("Should registration be blocked?", is_blocked)
# Output: Should registration be blocked? True
2. The not in Operator
The not in operator acts as the exact inverse of the in operator. It evaluates to True if the specified element is not present inside the target sequence. If the element is found inside the container, it returns False.
# A list of allowed, VIP guests invited to a private conference
vip_guest_list = ["Amit", "Sarah", "John", "Rahul"]
# A visitor arrives at the entrance gate
visitor_name = "Michael"
# Using 'not in' to verify if the visitor is an uninvited guest
access_denied = visitor_name not in vip_guest_list
print("Should security turn this visitor away?", access_denied)
# Output: Should security turn this visitor away? True