Sets
Quiz: counts toward finishing the lesson. Check: just for practice.
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.
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]], 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 = {"a", "b", "a", "c", "b"}
letters.add("c")
letters.add("d")
count = len(letters)
Predict what each variable holds after the program finishes. The program is not run for you. Change the values below to your predictions:
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.
Diagram: two overlapping circles (a Venn diagram) labeled set A and set B. Only the overlapping region in the middle, the elements shared by both circles, is shaded. That shaded middle is the intersection.
The union of two sets is a new set that contains every element that is in either set.
Diagram: two overlapping circles (a Venn diagram) labeled set A and set B. The entire area of both circles, including the overlap, is shaded. All of it together is the union.
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.
Diagram: two overlapping circles (a Venn diagram) labeled set A and set B. Only the part of circle A that does not overlap circle B is shaded. That shaded crescent is the difference A minus B.
Check your understanding. Predict the result. Remember that a set operation makes a new set and leaves the originals alone.
a = {1, 2, 3, 4}
b = {3, 4, 5}
only_b = b - a
size_a = len(a)
Predict what each variable holds after the program finishes. The program is not run for you. Change the values below to your predictions:
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.
Diagram: two overlapping circles (a Venn diagram) labeled set A and set B. Both circles are shaded except for the overlapping region in the middle, which is left blank. The two shaded crescents together are the symmetric difference.
You can loop through a set with a for loop:
Lists vs. Sets
How do you know when to use a list and when to use a set?
- 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.
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.
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.