Sets
A set stores values with no repeats. Its values have no positions, so you cannot use an index with a set. If you add a value that is already in the set, nothing happens. This makes set() a quick way to remove duplicates from a list:
names = ["Maya", "Ravi", "Maya", "Noor"]
unique = set(names)
unique.add("Ravi")
print(len(names))
print(len(unique))
print(sorted(unique))
Output:
4
3
['Maya', 'Noor', 'Ravi']
The second Maya is gone, and adding Ravi again changes nothing.
Why the example uses sorted
A set does not keep its values in any order. Here is the same set of strings, printed by two separate runs of one program:
{'Ravi', 'Isha', 'Noor', 'Maya'}
{'Maya', 'Ravi', 'Isha', 'Noor'}
So when the order matters, as in a report or an exercise, pass the set to sorted. You get back a list in a fixed order.
Compare two sets
morning = {"Maya", "Ravi", "Noor"}
evening = {"Ravi", "Noor", "Isha"}
print(sorted(morning & evening))
print(sorted(morning - evening))
Output:
['Noor', 'Ravi']
['Maya']
Python has operators for the common ways to compare two sets:
| Operator | Result |
|---|---|
first & second | Values in both sets |
first | second | Values in at least one of the sets |
first - second | Values found only in first |
first ^ second | Values found in one set but not the other |
In the example, & finds the names that are in both sets. - finds the names that are only in the morning set.
Checking whether a value is in a set is fast. So a set is a good fit for questions like "have I seen this value before?"
To make an empty set, write set(). If you write {}, you get an empty dictionary, not a set.
In the exercise, count the different words and print them.