Filter List to Keep Only Whitelist Values in Python
Filter a list of values to keep only those present in a predefined whitelist set using a list comprehension.
Python code
10 linesdef filter_whitelist(values, whitelist):
"""Return only values that are present in the whitelist set."""
return [value for value in values if value in whitelist]
if __name__ == "__main__":
raw_values = ["apple", "banana", "cherry", "date", "apple", "elderberry"]
allowed = {"apple", "banana", "date"}
result = filter_whitelist(raw_values, allowed)
print(result)
Output
['apple', 'banana', 'date', 'apple']
How it works
The list comprehension iterates through each value in the input list and includes it only if it appears in the whitelist set. Using a set for the whitelist gives fast O(1) membership lookup, making the overall operation O(n) instead of O(n*m) with a list. This preserves the original order of the input list while filtering out disallowed values. Duplicate values in the input are retained since they each pass the membership check independently.
Common mistakes
- Using a list instead of a set for the whitelist, which makes membership checks O(n) and slows down filtering on large datasets
- Forgetting that the result maintains input order and duplicates, not unique whitelisted values
- Passing whitelist as a string instead of a set/list, causing character-by-character checks
Variations
- Use a generator expression with next() to get the first whitelisted value only
- Use filter() with a lambda: list(filter(lambda x: x in whitelist, values))
Real-world use cases
- Filtering user-submitted tags against an approved category list before saving to a database.
- Sanitizing configuration parameters by removing unsupported options from a user-provided dictionary.
- Cleaning log entries by keeping only events from trusted source identifiers.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.