4. Smart Content Filter¶
Create a content moderation system.
Requirements:
Multiple blacklists (offensive, spam, etc.)
Context-aware filtering
Partial match detection
Whitelist exceptions
Severity levels
Detailed reporting
Learn Python MEMBERSHIP OPERATORS in 8 minutes! 🔎 (8:23)
In this chapter, you’ll master Python’s membership operators - in and not in. These operators test whether a value exists in a sequence like strings, lists, tuples, sets, or dictionaries. You’ll learn how to validate input, search for elements, check dictionary keys, and write cleaner conditional logic.
Use the in operator to test for membership in sequences
Use the not in operator to test for absence of membership
Apply membership operators to strings, lists, tuples, sets, and dictionaries
Validate user input efficiently with membership checks
Write cleaner conditionals using membership operators
Understand performance characteristics of membership tests across different data types
Membership operators test whether a value is found in a sequence (string, list, tuple, set, or dictionary).
Two Operators:
in - Returns True if value is found in sequence
not in - Returns True if value is NOT found in sequence
# in operator
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("orange" in fruits) # False
# not in operator
print("orange" not in fruits) # True
print("apple" not in fruits) # False
numbers = [1, 2, 3, 4, 5]
print(3 in numbers) # True
print(10 in numbers) # False
print(10 not in numbers) # True
colors = ("red", "green", "blue")
print("red" in colors) # True
print("yellow" in colors) # False
message = "Hello World"
print("H" in message) # True (case-sensitive!)
print("h" in message) # False
print("World" in message) # True (can check substrings)
print("world" in message) # False (case-sensitive)
unique_nums = {1, 2, 3, 4, 5}
print(3 in unique_nums) # True
print(10 in unique_nums) # False
person = {"name": "Alice", "age": 25, "city": "NYC"}
print("name" in person) # True (checks keys)
print("Alice" in person) # False (doesn't check values by default)
# Check values explicitly
print("Alice" in person.values()) # True
# Check key-value pairs
print(("name", "Alice") in person.items()) # True
valid_options = ("rock", "paper", "scissors")
choice = input("Choose: ").lower()
if choice in valid_options:
print("Valid choice!")
else:
print("Invalid! Try again.")
# Without membership operator (verbose)
if x == 1 or x == 2 or x == 3 or x == 4 or x == 5:
print("Found!")
# With membership operator (clean)
if x in [1, 2, 3, 4, 5]:
print("Found!")
# Check if email is blacklisted
blacklist = ["spam@example.com", "fake@example.com"]
if user_email in blacklist:
print("Access denied!")
password = "MyPassword123"
if "@" not in password:
print("Password must contain @")
Different data structures have different lookup speeds:
Fast (O(1) - Constant Time):
Sets: {1, 2, 3}
Dictionaries: {"key": "value"}
# Very fast for large datasets
large_set = set(range(1000000))
print(999999 in large_set) # Instant!
Slow (O(n) - Linear Time):
Lists: [1, 2, 3]
Tuples: (1, 2, 3)
Strings: "abc"
# Slower for large datasets
large_list = list(range(1000000))
print(999999 in large_list) # Must scan through all elements
Best Practice: Use sets for membership testing with large datasets!
word = "PYTHON"
letter = input("Guess a letter: ").upper()
if letter in word:
print(f"✓ Yes! '{letter}' is in the word")
else:
print(f"✗ No, '{letter}' is not in the word")
# Example runs:
# Guess a letter: P
# ✓ Yes! 'P' is in the word
# Guess a letter: Z
# ✗ No, 'Z' is not in the word
students = ["Alice", "Bob", "Charlie", "David"]
name = input("Enter student name: ")
if name in students:
print(f"{name} is enrolled")
else:
print(f"{name} is not enrolled")
if name not in students:
print("Would you like to enroll?")
email = input("Enter email: ")
# Check required characters
if "@" in email and "." in email:
# Check domain
if "gmail.com" in email or "yahoo.com" in email or "outlook.com" in email:
print("Email looks valid!")
else:
print("Unknown email provider")
else:
print("Invalid email format")
# Example:
# Enter email: user@gmail.com
# Email looks valid!
valid_grades = ['A', 'B', 'C', 'D', 'F']
grade = input("Enter grade: ").upper()
if grade in valid_grades:
print(f"Grade {grade} recorded")
# Additional checks
if grade in ['A', 'B']:
print("Excellent work!")
elif grade in ['C', 'D']:
print("Need improvement")
else:
print("Failed")
else:
print("Invalid grade! Use A, B, C, D, or F")
text = input("Enter text: ")
vowels = "aeiouAEIOU"
vowel_count = 0
for char in text:
if char in vowels:
vowel_count += 1
print(f"Vowels found: {vowel_count}")
# Example:
# Enter text: Hello World
# Vowels found: 3
# User database
admins = {"alice", "bob"}
moderators = {"charlie", "david"}
regular_users = {"eve", "frank", "grace"}
username = input("Enter username: ").lower()
if username in admins:
print("Access Level: Administrator")
print("Full access granted!")
elif username in moderators:
print("Access Level: Moderator")
print("Limited admin access")
elif username in regular_users:
print("Access Level: User")
print("Standard access")
else:
print("Unknown user - Access denied")
Fruit Checker: Create a program that checks if a fruit is in your shopping list.
Number Validator: Write a program that validates if input is in range 1-10 using membership operators.
Password Character Check: Check if a password contains required characters (@, #, $, etc.).
Color Validator: Create a list of valid colors and check user input against it.
Banned Words: Check if a message contains banned words from a list.
Username Availability: Check if a username is already taken from a list of existing users.
Multiple Criteria: Create a validator that checks if input meets multiple membership criteria.
Dictionary Permission System: Use dictionary keys to check user permissions.
Substring Search: Find all occurrences where a substring appears in a text.
Whitelist/Blacklist: Implement both whitelist (allowed) and blacklist (blocked) checks.
Smart Search: Build a case-insensitive search that handles partial matches using membership operators.
Set Operations: Use membership with set operations (union, intersection) for complex validation.
Nested Membership: Check membership in nested data structures (lists of dicts, etc.).
Performance Comparison: Compare membership testing performance between lists and sets with large datasets.
Custom Membership: Create a class that implements __contains__ to support custom membership logic.
Wrong:
word = "Python"
if "python" in word: # False - case mismatch!
print("Found")
Correct:
word = "Python"
if "python" in word.lower(): # True - convert to lowercase
print("Found")
Why: String membership is case-sensitive. Always normalize case for comparison.
Wrong:
person = {"name": "Alice", "age": 25}
if "Alice" in person: # False - checks keys, not values!
print("Found")
Correct:
person = {"name": "Alice", "age": 25}
if "Alice" in person.values(): # True - checks values
print("Found")
Why: in checks dictionary keys by default. Use .values() to check values.
Wrong:
# Slow for large lists - O(n) lookup
large_list = list(range(1000000))
for i in range(1000):
if i in large_list: # Scans entire list each time!
print("Found")
Correct:
# Fast with sets - O(1) lookup
large_set = set(range(1000000))
for i in range(1000):
if i in large_set: # Instant lookup!
print("Found")
Why: Lists have O(n) lookup time. Sets have O(1). Use sets for large membership tests.
Wrong:
# Checking if digit is in a number (wrong approach)
number = 12345
if 3 in number: # TypeError: argument of type 'int' is not iterable
print("Found")
Correct:
# Convert to string first
number = 12345
if "3" in str(number): # True
print("Found")
# Or use math operations
if 3 in [int(d) for d in str(number)]:
print("Found")
Why: in works with iterables. Convert numbers to strings to check digits.
Web forms validate input against allowed values:
ALLOWED_COUNTRIES = ["USA", "Canada", "UK", "Australia"]
if country in ALLOWED_COUNTRIES:
process_form()
Security systems check permissions:
if user.role in ["admin", "superuser"]:
grant_access()
Filter prohibited content:
BANNED_WORDS = ["spam", "abuse", "illegal"]
if any(word in message.lower() for word in BANNED_WORDS):
reject_message()
Search functionality checks for matches:
if search_term in product_name.lower():
display_product()
Build a comprehensive password validation system.
Requirements:
Check for required character types using membership
Banned words check
Common password blacklist
Minimum/maximum length
Sequential character detection
Provide specific feedback
Create a simple spelling checker.
Requirements:
Load dictionary of valid words
Check each word in text
Use set for fast membership testing
Suggest corrections for misspelled words
Handle punctuation
Case-insensitive checking
Build an IP blocking/allowing system.
Requirements:
Whitelist of allowed IPs
Blacklist of blocked IPs
IP range support
Logging of access attempts
Admin override capabilities
Performance optimized with sets
Create a content moderation system.
Requirements:
Multiple blacklists (offensive, spam, etc.)
Context-aware filtering
Partial match detection
Whitelist exceptions
Severity levels
Detailed reporting
Build an inventory checker for a game.
Requirements:
Check item ownership
Valid item database
Item categories with membership
Quest item requirements
Crafting recipe validation
Trade restrictions
Variables store data values that can be reused
Use if-elif-else for conditional logic
Test your code to ensure it works correctly
💡 These points cover the main concepts from the video tutorial to help reinforce your learning.