Python Sets
A set is a collection that keeps only unique items and has no fixed order.
Creating a Set
Write the items inside curly brackets {}:
Example
colors = {"red", "green", "blue", "red"}
print(colors)
print(len(colors)){'green', 'red', 'blue'}
3The second "red" disappeared because sets do not allow duplicates. The order you see may be different on your computer, because sets are unordered.
To create an empty set, write set(). Writing {} creates an empty dictionary, not a set.
Removing Duplicates From a List
A very common use of sets is to remove repeated values:
Example
cities = ["Karachi", "Lahore", "Karachi", "Quetta", "Lahore"]
unique = set(cities)
print(len(unique))
print(sorted(unique))3 ['Karachi', 'Lahore', 'Quetta']
No Indexing
Because sets have no order, you cannot use colors[0]. Instead, loop through the set or check if an item is in it:
Example
colors = {"red", "green"}
print("red" in colors)
for c in sorted(colors):
print(c)True green red
Adding and Removing Items
Example
skills = {"Python", "Excel"}
skills.add("SQL")
skills.update(["Git", "HTML"])
skills.remove("Excel")
skills.discard("Java") # no error even though Java is not there
print(sorted(skills))['Git', 'HTML', 'Python', 'SQL']
remove() raises an error if the item is missing. discard() does not.
Set Operations
Sets are great for comparing two groups. Imagine two classes at an institute:
Example
morning = {"Ali", "Sara", "Hamza", "Zainab"}
evening = {"Hamza", "Zainab", "Bilal"}
print(sorted(morning.union(evening)))
print(sorted(morning.intersection(evening)))
print(sorted(morning.difference(evening)))
print(sorted(morning.symmetric_difference(evening)))['Ali', 'Bilal', 'Hamza', 'Sara', 'Zainab'] ['Hamza', 'Zainab'] ['Ali', 'Sara'] ['Ali', 'Bilal', 'Sara']
| Method | Result | Short symbol |
|---|---|---|
union() | Items in either set | (pipe symbol) |
intersection() | Items in both sets | & |
difference() | Items in the first set only | - |
symmetric_difference() | Items in one set but not both | ^ |
For example, morning & evening gives the same result as morning.intersection(evening).
Frozen Sets
A frozenset is a set that cannot be changed after it is created, just like a tuple compared to a list:
Example
weekend = frozenset(["Sat", "Sun"])
print("Sun" in weekend)True
Exercise
Exercise
What does len({1, 2, 2, 3, 3, 3}) return?
