Python 3.3Free video16 minLesson 3 of 6 in Module 3
Sets
Keep unique items and ask membership questions fast.
Free sample. Everything in this module opens with a free account.
Watch or read the lesson: Sets
01Duplicates in a list, and set
In the previous lesson you learned about tuples, and saw how they let you store a group of values that cannot be changed after they are created. This lesson starts with a different problem.
Imagine you are tracking visitors to a website, and you have recorded five visits. Mia visited twice, Jack visited twice, and Sophia visited once:
visits = ["mia", "jack", "mia", "sophia", "jack"]
len(visits)
5
Here is a question: how many different people visited the website? If you check the length of the list, Python gives you 5. That is correct, because the list contains five entries. But you do not have five different visitors. You only have three: Mia, Jack and Sophia.
So how can you get Python to count each person only once?
set
Python has a built-in type called setKey termAn unordered collection in which each value appears at most once. An empty set is set().. Pass the list of visits to it, store the result in a variable called unique, and check its length:
unique = set(visits)
len(unique)
3
Python gives you 3, exactly what you wanted. If you sort the result, so that the names appear in alphabetical order, you can see them:
sorted(unique)
['jack', 'mia', 'sophia']
Each name appears only once. So what happened to the duplicates? And how does Python make checking whether someone is in a set so efficient? Those are the two questions this lesson explores.
02Creating a set: set literals and set()
Start with the basics. A setKey termAn unordered collection in which each value appears at most once. An empty set is set(). is a collection of unique values. That means each value can appear at most once. If you try to add the same value again, the set does not create another copy of it.
How do you create a set? One way is to use curly brackets. This set is written with the numbers 3, 1, 3, 2 and 1. Notice that both 3 and 1 are repeated:
{3, 1, 3, 2, 1}
{1, 2, 3}
Python gives you a set containing just three values: 1, 2 and 3. The repeated values are gone. And if you check its length, you get 3:
len({3, 1, 3, 2, 1})
3
How set() removed the duplicate visits
This is exactly what happened with the website visitors. When you passed the visits list to set(), Python went through the values one by one and added them to a new set:
- The first time it encountered Mia, it added her name.
- The first time it encountered Jack, it added his name too.
- When Mia appeared again, she was already in the set, so Python did not add another copy.
- The same happened when Jack appeared again.
By the end, the set held just three unique names.
Sets have no order you can rely on
You might notice something interesting when you display a set: the values do not always appear in the order you entered them. That is an important property of sets. Unlike lists and tuples, sets do not preserve an order that you can rely on.
For example, when you display the set of visitor names, Python might show Sophia first on one machine and Jack first on another, and the order can change between Python sessions. That is why this lesson never shows a set of names directly.
So if you need the names in a predictable order, what should you do? Use sorted():
sorted(unique)
['jack', 'mia', 'sophia']
Python gives you a new list with the names arranged alphabetically: Jack, Mia and Sophia. The set itself is unchanged.
03add, remove, discard, and the empty set
Here is another difference between sets and tuples. A tuple is immutable, but a regular set is mutable: you can add and remove values after creating it.
add
Return to the unique visitors, and suppose Tom visits the website. You want to add his name to the set. With a list you would use append(), but sets do not have an append method. That makes sense: append means adding something to the end, and a set does not have a meaningful first or last position.
Instead, you use a method called add():
unique.add("tom")
print(sorted(unique))
print(len(unique))
['jack', 'mia', 'sophia', 'tom']
4
Now the set contains four different names: Mia, Jack, Sophia and Tom. But what if Mia visits again? Add her name and check the length:
unique.add("mia")
len(unique)
4
It is still 4, because Mia is already in the set, and adding an existing value does not create a duplicate.
remove
What about removing values? Sets have two useful methods for that: remove() and discard(). Start with remove. Suppose you want to remove Jack:
unique.remove("jack")
sorted(unique)
['mia', 'sophia', 'tom']
Jack is no longer in the set. Pretty straightforward. But what happens if you try to remove someone who is not there, such as Zoe? Think it through before reading on.
I have a guess. Show meHide the answer
unique.remove("zoe")
KeyError: 'zoe'
Python raises a KeyError, because Zoe is not in the set. Remember the lesson on lists: when you tried to remove a missing value from a list, Python raised a ValueError. With sets, the remove method raises a KeyError instead.
discard
Sometimes you do not want an error just because a value is missing. Maybe you are removing a visitor from a temporary collection, and it is perfectly fine if that person is not there. That is where discard() comes in:
unique.discard("zoe")
sorted(unique)
['mia', 'sophia', 'tom']
This time nothing goes wrong. Python simply leaves the set unchanged. So here is the difference:
- Both methods remove a value when it is present.
- If the value is missing,
remove()raises an error, whilediscard()does nothing.
Use remove when a missing value indicates something unexpected, and use discard when it is fine for the value not to exist.
The empty set
Here is a small question that catches a lot of beginners: how do you create an empty set? You might think you can simply write two empty curly brackets, {}, because that is what you used to create a set earlier. If you check the type of these empty curly brackets, is it a set, or something else? Think it through before reading on.
I have a guess. Show meHide the answer
type({})
dict
Python tells you it is a dictionary, not a set. Why? Because dictionaries also use curly brackets, and empty curly brackets represent an empty dictionary in Python. You will learn about dictionaries in the next lesson.
For now, if you want an empty set, you need to use the set function:
empty = set()
type(empty)
set
empty
set()
04Sets are unordered and not subscriptable
Now for accessing elements. Remember how you accessed items in lists and tuples? You used square brackets with an index, and index zero gave you the first element. Can you do that with a set? No, you cannot:
unique[0]
TypeError: 'set' object is not subscriptable
Python raises a TypeError, and the message says that a set object is not subscriptable. Subscriptable is the term Python uses for objects that support square-bracket access, like lists and tuples. A set does not have indexed positions, so you cannot ask for the element at index zero, or for the last element at index minus one.
Looping through a set
Here is the good news: you can still loop through a set, because sets are iterable. A for loop goes through every value, and Python gives you each element once. Just remember that the iteration order is not guaranteed. So if you want to print the names alphabetically, loop over sorted(unique):
for name in sorted(unique):
print(name)
mia
sophia
tom
05Union, intersection and difference
Now for something sets are especially good at: comparing collections.
Imagine you are running two online courses, one in Python and the other in statistics. Four students are enrolled in Python: Mia, Jack, Sophia and Tom. Three students are enrolled in statistics: Jack, Tom and Zoe. Store these groups as two sets, one called python and the other called stats.
Sets are a natural fit here. Within each course, you only care whether a student is enrolled. You do not need to store their name more than once.
Union
Now ask a few questions about these two groups. First: who is enrolled in either course? In other words, you want everyone who is enrolled in Python, statistics, or both. In set terminology, that is called a union, and Python gives you an operator for it: the vertical bar, |.
python = {"mia", "jack", "sophia", "tom"}
stats = {"jack", "tom", "zoe"}
sorted(python | stats)
['jack', 'mia', 'sophia', 'tom', 'zoe']
python | stats gives you a new set containing all five students. (It is wrapped in sorted() here so that the names come out in a predictable order.) Notice that Jack and Tom appear in both original sets, but in the union each name appears only once, because the result is a set too.
Intersection
Here is another question: who is enrolled in both courses? Not either course: both. That is called an intersectionKey termEvery value in both sets, a & b., and Python uses the ampersand operator, &, for it. Before you run python & stats, can you identify the students who belong to both groups? Think it through before reading on.
I have a guess. Show meHide the answer
sorted(python & stats)
['jack', 'tom']
The answer is Jack and Tom. Those are the two students enrolled in both Python and statistics.
Difference
Now a slightly different question: who is enrolled in Python, but not in statistics? For that, you use the set differenceKey termThe values in the first set that are not in the second, a - b. operation, and the operator is the minus sign, -:
sorted(python - stats)
['mia', 'sophia']
Python gives you Mia and Sophia, because those two students appear in the Python set but not in the statistics set.
Here is something important: the order of the sets matters for difference. If you reverse them:
sorted(stats - python)
['zoe']
You get Zoe only, because Zoe is enrolled in statistics but not in Python. So set difference is not necessarily the same in both directions.
What each operation answers
To connect these operations to the questions they answer:
- Union,
python | stats: everyone in either set. - IntersectionKey termEvery value in both sets,
a & b.,python & stats: everyone in both sets. - DifferenceKey termThe values in the first set that are not in the second,
a - b.,python - stats: everyone in the first set but not the second.
06Membership testing: linear scan versus hash lookup
Now return to the second question from the beginning of this lesson: why are sets so efficient when you want to check whether a value exists?
Remember the website visitors. Suppose you want to check whether Sophia has visited. You write "sophia" in unique:
"sophia" in unique
True
Python returns True, because Sophia is still in the set. You could do the same thing with a list and get the same answer. The difference is how Python finds that answer.
A list is scanned from the beginning
Start with a list. Imagine you have a list containing one million numbers, from 0 up to 999,999. Suppose you ask whether the last number, 999,999 (six nines), is in numbers_list:
numbers_list = list(range(1000000))
999999 in numbers_list
True
To answer, Python needs to search through the list. It starts checking elements from the beginning: first 0, then 1, then 2, and so on, until it finds the value you are looking for. Because this number is at the very end, Python has to check the entire list before finding it.
Now imagine you are checking for a number that is not in the list at all. In that case, Python still has to go through every element before it can conclude that the value is missing. This one-by-one search is called a linear scan, and as the list gets larger, this kind of membership check can take longer.
A set uses hashing
Now compare that with a set. Create a set containing those same one million integers, and check whether 999,999 is in numbers_set:
numbers_set = set(range(1000000))
999999 in numbers_set
True
The result is still True. But Python does not need to scan through every element from the beginning. Instead, sets use something called hashing.
Hashing might sound technical, but the basic idea is quite intuitive:
- When you add a value to a set, Python computes a number from that value. That number is called a hashKey termA number Python computes from a value, which a set uses to decide where the value is stored. A dictionary uses its keys' hashes in the same way..
- Python uses the hash to help determine where to store the value internally.
- When you want to check whether that value exists, Python computes its hash again, uses it to find where to look, and then compares the stored value with the value you are searching for.
So instead of checking every element one by one, Python can usually narrow down the search very quickly.
Hash collisions
That does not mean every lookup is guaranteed to take exactly the same amount of time. Sometimes different values have the same hash. That is called a hash collision, and Python has to do some additional checking to resolve it.
07Hashable values: what a set can hold
Hashing also explains another important rule about sets: not every Python object can be stored inside a set.
Remember the GPS coordinates from the tuples lesson? Suppose you represent a coordinate as a list containing two floats, and then try to put that list inside a set. What do you think happens? Think it through before reading on.
I have a guess. Show meHide the answer
{[40.7128, -74.006]}
TypeError: unhashable type: 'list'
Python raises a TypeError that says unhashable type: 'list'. What does that mean?
As you have seen, sets use hashes to organize and find their elements. For that to work reliably, an element must be hashableKey termA value whose hash stays stable during its lifetime and whose equal values have equal hashes, so it can be a set member or dictionary key: numbers, strings, and tuples of hashable values. Lists, sets and dictionaries are not.: its hash must stay stable during its lifetime, and equal values must have equal hashes.
A list can change: you can add values, remove values, or replace them. That is one reason Python lists are not hashable, so you cannot use a list directly as an element of a set. The same restriction applies to ordinary dictionaries and to mutable sets. A set cannot hold another set:
{{1, 2}}
TypeError: unhashable type: 'set'
Tuples
What about tuples? Tuples are immutable, so a tuple containing hashable values, like integers, floats or strings, is normally hashable too. That means coordinates stored as tuples can go into a set, and a repeated coordinate is kept only once:
places = {(40.7128, -74.006), (41.8781, -87.6298), (40.7128, -74.006)}
len(places)
2
08Recap and challenge: sets, set operations and hashing
You started with five website visits from three different people, and learned how a set removes duplicates by keeping each value only once. Then you saw how to create sets, add and remove elements, and why sets do not support indexing or guarantee a particular order. You also learned that empty curly brackets create a dictionary, not a set, so an empty set is written set().
Then you explored set operations: union, intersection and difference, and used them to compare the students enrolled in two different courses. Finally, you learned that sets use hashing, which lets Python locate values efficiently without scanning the entire collection, and that this is why a set's elements must be hashable.
Your challenge
Imagine you are managing a newsletter, and you have two lists of signups, one for June and another for July:
june = ["mia", "jack", "sophia", "mia", "tom"]
july = ["jack", "zoe", "lin", "zoe", "sophia"]
Some people signed up more than once, and some people signed up in both months. Use sets to answer three questions:
- How many different people signed up across the two months?
- Who signed up in both June and July?
- Who signed up in July but not in June?
In the next lesson, you will build on the idea of hashing. Instead of simply checking whether a value exists, you will use it to find another value associated with it.
Key terms: Sets
The words this lesson introduces, each in one line. The module’s glossary collects them all, and the AI glossary has every term across the courses.
- difference
- The values in the first set that are not in the second,
a - b. - frozenset
- An immutable, hashable set:
frozenset({1, 2}). - hash
- A number Python computes from a value, which a set uses to decide where the value is stored. A dictionary uses its keys' hashes in the same way.
- hashable
- A value whose hash stays stable during its lifetime and whose equal values have equal hashes, so it can be a set member or dictionary key: numbers, strings, and tuples of hashable values. Lists, sets and dictionaries are not.
- intersection
- Every value in both sets,
a & b. - KeyError
- The exception for a missing dictionary key or an absent member passed to
set.remove. - set
- An unordered collection in which each value appears at most once. An empty set is
set().
Quiz: Sets
Your first pick on each question is the one that counts. Getting one wrong here is how the lesson sticks.