How to Remove Banned Values from a List in Python

Filters a list by removing elements present in a banned set, preserving the original order.

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

Python code

10 lines
Python 3.9+
def remove_banned(values, banned):
    banned_set = set(banned)
    return [item for item in values if item not in banned_set]


if __name__ == "__main__":
    values = [1, 2, 3, 4, 5, 2, 6, 3, 7]
    banned = [2, 3]
    result = remove_banned(values, banned)
    print(result)

Output

stdout
[1, 4, 5, 6, 7]

How it works

The function converts the banned list to a set for O(1) average lookups, and then uses a list comprehension to iterate through the original list, including only items not in the banned set. This approach is concise and efficient, with a time complexity of O(n + m) for n values and m banned items. The order of the original list is preserved because list comprehensions maintain sequence.

Common mistakes

  • Forgetting to convert banned to a set, leading to O(n*m) complexity
  • Returning a generator instead of a list without wrapping in list()
  • Modifying the list while iterating over it

Variations

  1. Use the filter function: list(filter(lambda x: x not in banned_set, values))
  2. Use a for loop with append for clarity

Real-world use cases

  • Filtering out blocked IP addresses from a request log before analysis.
  • Removing excluded product IDs from an inventory batch before processing.
  • Excluding banned words from a user-generated content list before moderation.

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.