How to Remove Banned Words from a Set in Python
Filter a vocabulary set by removing banned words using the .difference() method.
Python code
10 linesvocabulary = {"apple", "banana", "cherry", "date", "elderberry"}
banned_words = {"banana", "date", "fig"}
# Remove banned words using set difference
allowed_words = vocabulary.difference(banned_words)
print("Original vocabulary:", sorted(vocabulary))
print("Banned words:", sorted(banned_words))
print("Allowed words after filtering:", sorted(allowed_words))
print("Number of allowed words:", len(allowed_words))
Output
Original vocabulary: ['apple', 'banana', 'cherry', 'date', 'elderberry']
Banned words: ['banana', 'date', 'fig']
Allowed words after filtering: ['apple', 'cherry', 'elderberry']
Number of allowed words: 3
How it works
set.difference() returns a new set containing elements present in the first set but not in the second. It does not modify the original set, so vocabulary remains unchanged. Using sets ensures fast membership testing and automatically removes duplicates. The sorted() call is just for readable output ordering since sets are unordered.
Common mistakes
- Confusing `difference()` with `symmetric_difference()` which returns elements in either set but not both.
- Forgetting that `difference()` returns a new set and neither input set is modified.
- Assuming set operations preserve insertion order — they don't, so always sort if order matters for output.
Variations
- Use the `-` operator: `allowed_words = vocabulary - banned_words`
- Filter with a set comprehension: `{word for word in vocabulary if word not in banned_words}`
Real-world use cases
- Filtering offensive or blocked terms from user-generated tags before storing in a database.
- Removing excluded stock tickers from a portfolio watchlist during market data processing.
- Cleaning a list of allowed IP addresses by excluding blacklisted ranges in a security script.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.