Sets
Introduction
You may know sets from math class. A set is an unordered collection of unique elements. Adding a duplicate does not change a set. You can add new elements, so sets are mutable. The elements themselves must be immutable (unchangeable), so a set cannot contain lists, dictionaries, or other sets. A set can hold values of different types, or be empty.
The type hints are explained in the next section. For now, notice that the empty set empty still has a hint, because an empty set needs to say what it could hold. We chose int for it.
Type hinting with sets
You can add a type hint to a set with set.
The some_ints variable is declared as a set[int], meaning a set of integers. The some_elements variable is declared as a set[int | str | float | bool | tuple[int, int, int]], meaning a set of elements that can be integers, strings, floats, booleans, or tuples. The empty variable is declared as a set, meaning a set with no restriction on the element type.
You cannot index or slice sets, because they have no order.
You can use in and not in to check whether a value is in the set:
You can add elements to a set or remove elements from a set:
Check your understanding. Predict the result. Think about what a set keeps when the same value shows up again.
letters: set[str] = {"a", "b", "a", "c", "b"}
letters.add("c")
letters.add("d")
count: int = len(letters)
Predict what each variable holds after the program finishes. The program is not run for you. Replace each None in the box below with your prediction, and give each variable a type hint, like name: type = value. Then press Run to find out if you are right. Write text in quotes, like "abc". Write a list in square brackets, like [1, 2, 3]. Write a set in curly braces, like {1, 2, 3}.
final_countis the value ofcountat the end
Hint 1
A set holds each value at most once, whether it came from the braces or from add.
The len function tells you how many elements are in a set:
The clear method empties a set:
Set Operations
Python has operators for common set operations. The most common set operations are union, intersection, difference, and symmetric difference. Each of these operations produces a new set and leaves the original sets unchanged.
The intersection of two sets is a new set that contains every element that is in both sets.
The union of two sets is a new set that contains every element that is in either set.
The difference of two sets is a new set that contains every element that is in the first set except for the elements that are also in the second set. This operation is not "symmetric": the result can change depending on which set comes first.
Check your understanding. Predict the result. Remember that a set operation makes a new set and leaves the originals alone.
a: set[int] = {1, 2, 3, 4}
b: set[int] = {3, 4, 5}
only_b: set[int] = b - a
size_a: int = len(a)
Predict what each variable holds after the program finishes. The program is not run for you. Replace each None in the box below with your prediction, and give each variable a type hint, like name: type = value. Then press Run to find out if you are right. Write text in quotes, like "abc". Write a list in square brackets, like [1, 2, 3]. Write a set in curly braces, like {1, 2, 3}.
final_only_bis the value ofonly_bat the endfinal_size_ais the value ofsize_aat the end
Hint 1
b - a keeps what is in b but not in a. The original sets stay as they were.
The symmetric difference of two sets is a new set that contains every element that is in either set except the elements that are in both sets. This is the same as the union minus the intersection.
You can loop through a set with a for loop:
Explanation
& is intersection, | is union, - is difference, ^ is symmetric difference. {} is an empty dict, so an empty set is set().
Lists vs. Sets
A list and a set differ in four ways:
- A set cannot contain duplicate elements, but a list can.
- A set can only contain values that are immutable, but lists can contain mutable values.
- A list is ordered, so you can know that its elements will be looped over or printed in a fixed order. Sets are unordered, so that is not guaranteed for them.
- Checking whether a certain value is in a list takes time proportional to the length of the list, but doing so in a set is very fast, regardless of the size of the set.
Check your understanding. Predict the result. Turning a list into a set drops the duplicates.
names: list[str] = ["Ana", "Bo", "Ana", "Cy", "Bo"]
unique: set[str] = set(names)
list_count: int = len(names)
set_count: int = len(unique)
has_cy: bool = "Cy" in unique
Predict what each variable holds after the program finishes. The program is not run for you. Replace each None in the box below with your prediction, and give each variable a type hint, like name: type = value. Then press Run to find out if you are right.
final_list_countis the value oflist_countat the endfinal_set_countis the value ofset_countat the endfinal_has_cyis the value ofhas_cyat the end
Hint 1
List the distinct names first. Then count the original list and the distinct names separately.
Explanation
Mutable means it can change after it is created.
Set Comprehensions
A set comprehension looks just like a list comprehension except it uses curly braces instead of square brackets. For example, if you have a list of names that possibly contains duplicates, and you would like to filter out any names that aren't palindromes (ignoring case) and get rid of duplicates at the same time, you could create a set like so:
Comparing a name to its reverse ([::-1]) checks for a palindrome. Calling lower() first makes the check ignore case. The curly braces create a set, which drops duplicates automatically.
Explanation
A comprehension has a result, a for ... in loop and an optional if filter. Curly braces make a set, square brackets make a list.
Quizzes
- Write your own function called
unionizefor finding the union of two sets. Your function should take as parameters two sets, and return a new set that is the union of those two sets. Do not use Python's built-in union functionality.
- Write your own function called
intersectfor finding the intersection of two sets. Your function should take as parameters two sets, and return a new set that is the intersection of those two sets. Do not use Python's built-in intersection functionality.
- Write your own function called
sym_difffor finding the symmetric difference of two sets. Your function should take as parameters two sets, and return a new set that is the symmetric difference of those two sets. Do not use Python's built-in symmetric difference functionality.
Projects
Practice what you learned in your own editor. Each project has its own page.