Practical Examples
Real-World Scenarios for List Membership
1. User Authentication
## Checking user permissions
allowed_users = ['admin', 'manager', 'supervisor']
current_user = 'admin'
if current_user in allowed_users:
print("Access granted")
else:
print("Access denied")
2. Data Filtering
## Filtering valid entries
raw_data = [10, -5, 15, 'invalid', 20, 0, 'error']
valid_numbers = [num for num in raw_data if isinstance(num, int) and num > 0]
print(valid_numbers) ## Output: [10, 15, 20]
3. Duplicate Removal
## Removing duplicates efficiently
def remove_duplicates(input_list):
unique_items = []
for item in input_list:
if item not in unique_items:
unique_items.append(item)
return unique_items
original_list = [1, 2, 2, 3, 4, 4, 5]
cleaned_list = remove_duplicates(original_list)
print(cleaned_list) ## Output: [1, 2, 3, 4, 5]
Membership Workflow
graph TD
A[Input List] --> B{Check Membership}
B -->|Element Present| C[Process Element]
B -->|Element Absent| D[Handle Exception]
C --> E[Continue Execution]
D --> F[Take Alternative Action]
4. Validation Techniques
## Complex validation example
def validate_email(email):
valid_domains = ['gmail.com', 'yahoo.com', 'hotmail.com']
## Check domain membership
domain = email.split('@')[-1]
return domain in valid_domains
## Test email validation
test_emails = [
'[email protected]',
'[email protected]',
'[email protected]'
]
for email in test_emails:
print(f"{email}: {validate_email(email)}")
Method |
Time Complexity |
Recommended Use |
in operator |
O(n) |
Small to medium lists |
Set membership |
O(1) |
Large lists |
List comprehension |
O(n) |
Filtering complex conditions |
5. Advanced Membership Checking
## Multi-condition membership
def advanced_filter(items):
special_numbers = [10, 20, 30]
special_chars = ['@', '#', '$']
filtered_items = [
item for item in items
if (isinstance(item, int) and item in special_numbers) or
(isinstance(item, str) and any(char in item for char in special_chars))
]
return filtered_items
test_data = [10, 'hello@world', 15, '#tag', 20, 'test']
result = advanced_filter(test_data)
print(result) ## Output: [10, 'hello@world', 20, '#tag']
LabEx Pro Tip
In LabEx development environments, always consider converting lists to sets for more efficient membership testing, especially with large datasets.