Python Sets Examples
Short, runnable programs that show python sets in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Sets lesson.
1Counting the different words in a sentence
split() breaks the text into words; the set keeps one of each. sorted() gives a stable, alphabetical result.
sentence = "the cat and the dog and the bird"
words = sentence.split()
unique = set(words)
print(len(words), "words,", len(unique), "different")
print(sorted(unique))Expected output8 words, 5 different
['and', 'bird', 'cat', 'dog', 'the']
2Checking a form for missing fields
Difference finds what is missing or unexpected, and <= asks whether every required field is present.
required = {"name", "email", "password"}
submitted = {"name", "password", "age"}
print("Missing:", sorted(required - submitted))
print("Unexpected:", sorted(submitted - required))
print("All present?", required <= submitted)Expected outputMissing: ['email']
Unexpected: ['age']
All present? False
3Blocking messages that contain banned words
The intersection of a message's words and the banned set is empty (which counts as False) unless a banned word appears.
banned = {"spam", "scam", "free"}
messages = ["hello there", "win a free phone", "meeting at 3", "this is not spam"]
for msg in messages:
if set(msg.split()) & banned:
print("Blocked:", msg)
else:
print("OK:", msg)Expected outputOK: hello there
Blocked: win a free phone
OK: meeting at 3
Blocked: this is not spam
4add(), discard() and -= on seat numbers
Small whole numbers make the set's printed order predictable. discard() doesn't complain about a missing value, and -= removes every value found in another set.
seats = {1, 2, 3, 4, 5}
seats.discard(3)
seats.discard(9)
seats.add(6)
print(seats)
seats -= {2, 6}
print(seats, len(seats))Expected output{1, 2, 4, 5, 6}
{1, 4, 5} 3
Practise next
Python Sets exercises → Back to the lesson
Python Lists examplesPython Tuples examplesPython Set Operations examplesPython Dictionaries examples