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.
Python code
10 linesdef 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
[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
- Use the filter function: list(filter(lambda x: x not in banned_set, values))
- 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
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.