Sets: No Duplicates Allowed

What is a set?

A set is a collection where every value appears only once. It uses curly brackets { }. Sets have no order, so you can't use an index on them.

numbers = {3, 1, 3, 2, 1}
print(numbers)
print(len(numbers))

Output

{1, 2, 3}
3

Removing duplicates from a list

visitors = ["asha", "ravi", "asha", "meena", "ravi"]
unique = set(visitors)
print(len(unique), "unique visitors")
print(sorted(unique))

Output

3 unique visitors
['asha', 'meena', 'ravi']

Adding and checking

tags = {"python", "beginner"}
tags.add("coding")
tags.add("python")
print("python" in tags)
print(sorted(tags))

Output

True
['beginner', 'coding', 'python']

Comparing groups

Think of it like this: Two friends compare the songs they like. Which songs do they both like? Which songs does only one of them like?

asha = {"Song A", "Song B", "Song C"}
ravi = {"Song B", "Song C", "Song D"}
print("Both like:", sorted(asha & ravi))
print("Either likes:", sorted(asha | ravi))
print("Only Asha:", sorted(asha - ravi))

Output

Both like: ['Song B', 'Song C']
Either likes: ['Song A', 'Song B', 'Song C', 'Song D']
Only Asha: ['Song A']
SymbolNameMeaning
&intersectionin both sets
|unionin either set
-differencein the first set but not the second

Common mistake: {} makes an empty dictionary, not a set. For an empty set write set().

HOME LEARN COMMUNITY DASHBOARD