How to Remove Banned Words from a Set in Python

Filter a vocabulary set by removing banned words using the .difference() method.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 16 views 0 copies

Python code

10 lines
Python 3.9+
vocabulary = {"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

stdout
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

  1. Use the `-` operator: `allowed_words = vocabulary - banned_words`
  2. 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

Run this sample

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

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.