Membership Operators

Code Examples

Example 1

When used with strings, both operators check if a substring exists within the larger string. This is case-sensitive, so "Python" and "python" are treated as different substrings. You can check for individual characters, words, or longer phrases.

# Checking substrings and characters in strings
message = "Hello, welcome to Python programming!"

# Using 'in' operator
contains_python = "Python" in message
print(contains_python)  # Output: True

contains_java = "Java" in message
print(contains_java)  # Output: False

# Case sensitivity matters
contains_python_lowercase = "python" in message
print(contains_python_lowercase)  # Output: False

# Checking for characters
has_spaces = " " in message
print(has_spaces)  # Output: True

# Using 'not in' operator
no_java = "Java" not in message
print(no_java)  # Output: True

no_python = "Python" not in message
print(no_python)  # Output: False

# Practical example with validation
email = "user@example.com"
if "@" not in email:
    print("Invalid email: missing @ symbol")
else:
    print("Email format looks valid")  # This will print

Example 2

Lists work straightforwardly with both membership operators. The in operator returns True if the value exists in the list, while not in returns True if the value doesn't exist. This is useful for checking prerequisites, validation, and filtering operations.

# Working with lists
fruits = ["apple", "banana", "orange", "mango"]
vegetables = ["carrot", "broccoli", "spinach", "potato"]

# Using 'in' operator
has_apple = "apple" in fruits
print(has_apple)  # Output: True

has_pear = "pear" in fruits
print(has_pear)  # Output: False

# Using 'not in' operator
no_tomato = "tomato" not in vegetables
print(no_tomato)  # Output: True

no_carrot = "carrot" not in vegetables
print(no_carrot)  # Output: False

# Practical example with conditional statements
shopping_list = ["milk", "bread", "eggs", "cheese"]
item_to_buy = "milk"

if item_to_buy in shopping_list:
    print(f"{item_to_buy} is already on the shopping list")  # This will print
else:
    shopping_list.append(item_to_buy)
    print(f"Added {item_to_buy} to the shopping list")

# Check for items NOT on the list
essential_items = ["milk", "bread", "butter"]
missing_items = []

for item in essential_items:
    if item not in shopping_list:
        missing_items.append(item)

print("Missing items:", missing_items)  # Output: Missing items: ['butter']

Example 3

Tuples work exactly like lists with membership operators. Since tuples are immutable, they're often used to store constant values like valid options, and membership operators help validate against these constants.

# Working with tuples
coordinates = (10, 20, 30, 40, 50)
days_of_week = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")

# Using 'in' operator
has_30 = 30 in coordinates
print(has_30)  # Output: True

has_35 = 35 in coordinates
print(has_35)  # Output: False

is_weekday = "Monday" in days_of_week
print(is_weekday)  # Output: True

# Using 'not in' operator
not_35 = 35 not in coordinates
print(not_35)  # Output: True

not_monday = "Monday" not in days_of_week
print(not_monday)  # Output: False

# Practical example with validation
valid_grades = ("A", "B", "C", "D", "F")
student_grade = "B+"

if student_grade in valid_grades:
    print("Grade is valid")
else:
    print("Invalid grade entered")  # This will print

if student_grade not in valid_grades:
    print(f"'{student_grade}' is not a standard grade")  # This will print

Example 4

With dictionaries, membership operators check keys by default, not values. To check values, you must use .values(). To check key-value pairs, you would use .items(). This distinction is crucial when working with dictionaries.

# Working with dictionaries
student = {
    "name": "Alex",
    "age": 21,
    "major": "Computer Science",
    "gpa": 3.8
}

# Using 'in' operator (checks keys by default)
has_name_key = "name" in student
print(has_name_key)  # Output: True

has_grade_key = "grade" in student
print(has_grade_key)  # Output: False

# Using 'not in' operator (checks keys by default)
no_grade_key = "grade" not in student
print(no_grade_key)  # Output: True

no_name_key = "name" not in student
print(no_name_key)  # Output: False

# Checking values (not keys)
has_alex_value = "Alex" in student.values()
print(has_alex_value)  # Output: True

no_bob_value = "Bob" not in student.values()
print(no_bob_value)  # Output: True

# Practical example with user data
user_profile = {"username": "john_doe", "email": "john@email.com"}
required_fields = ["username", "email", "password"]

missing_fields = []
for field in required_fields:
    if field not in user_profile:
        missing_fields.append(field)

if missing_fields:
    print("Missing required fields:", missing_fields)  # Output: Missing required fields: ['password']
else:
    print("All required fields are present")

Example 5

Sets are particularly efficient for membership testing because they use hash tables internally. This makes membership checks very fast, especially with large collections. Sets are ideal when you need to frequently check if items exist in a collection.

# Working with sets
allowed_colors = {"red", "green", "blue", "yellow"}
forbidden_ingredients = {"peanuts", "shellfish", "dairy"}

# Using 'in' operator
is_red_allowed = "red" in allowed_colors
print(is_red_allowed)  # Output: True

is_purple_allowed = "purple" in allowed_colors
print(is_purple_allowed)  # Output: False

has_peanuts = "peanuts" in forbidden_ingredients
print(has_peanuts)  # Output: True

# Using 'not in' operator
no_purple = "purple" not in allowed_colors
print(no_purple)  # Output: True

no_red = "red" not in allowed_colors
print(no_red)  # Output: False

safe_ingredient = "flour" not in forbidden_ingredients
print(safe_ingredient)  # Output: True

# Practical example with permissions
user_permissions = {"read", "write", "delete"}
admin_permissions = {"read", "write", "delete", "admin", "manage_users"}

action = "delete"
if action in user_permissions:
    print(f"User can perform: {action}")  # This will print
else:
    print(f"Access denied for: {action}")

special_action = "manage_users"
if special_action not in user_permissions:
    print(f"User cannot perform: {special_action}")  # This will print

Example 6

When checking multiple values, you can combine membership operators with logical operators (and, or) or use built-in functions like any() and all() for more elegant solutions. How all() works: - all() returns True if all elements in the iterable are True. - The expression diet not in dietary_preferences is checked for each diet in restricted_diets. Check each diet: - "keto" not in dietary_preferences → True - "paleo" not in dietary_preferences → True - "low-carb" not in dietary_preferences → True Since all three are not in the user's preferences → all(True, True, True) → āœ… True. How any() works: - any() returns True if at least one element in the iterable is True. Check each diet: - "keto" in dietary_preferences → False - "paleo" in dietary_preferences → False - "low-carb" in dietary_preferences → False So any(False, False, False) → āŒ False.

# Check if any of several values exist in a collection
dietary_preferences = ["vegetarian", "gluten-free", "dairy-free"]
restricted_diets = ["keto", "paleo", "low-carb"]

# Using 'in' with multiple checks
is_vegan = "vegan" in dietary_preferences                   # False
is_vegetarian = "vegetarian" in dietary_preferences    # True
is_plant_based = is_vegan or is_vegetarian                   # False or True → True
print("Has plant-based preference:", is_plant_based)  # Output: Has plant-based preference: True

# Using 'not in' with multiple checks
has_no_restrictions = all(diet not in dietary_preferences for diet in restricted_diets)
print("Has no restricted diets:", has_no_restrictions)  # Output: Has no restricted diets: True

# Method using any() function
has_any_restriction = any(diet in dietary_preferences for diet in restricted_diets)
print("Has restricted diet:", has_any_restriction)  # Output: Has restricted diet: False