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.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 12 views 0 copies

Python code

10 lines
Python 3.9+
def 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

stdout
['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

  1. Use a generator expression with next() to get the first whitelisted value only
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.