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_count is the value of count at 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.

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.

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.

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: 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_b is the value of only_b at the end
  • final_size_a is the value of size_a at 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.

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:

Recall: click each blank to check yourself

Fill in the operator or name for each result.

a: set[int] = {1, 2, 3}
b: set[int] = {3, 4}
both: set[int] = a  b  # 3
either: set[int] = a  b  # 1, 2, 3, 4
only_a: set[int] = a  b  # 1, 2
one_side: set[int] = a  b  # 1, 2, 4
empty: set[int] = ()
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:

  1. A set cannot contain duplicate elements, but a list can.
  2. A set can only contain values that are immutable, but lists can contain mutable values.
  3. 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.
  4. 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_count is the value of list_count at the end
  • final_set_count is the value of set_count at the end
  • final_has_cy is the value of has_cy at the end
Hint 1

List the distinct names first. Then count the original list and the distinct names separately.

Recall: click each blank to check yourself

Lists, dictionaries and sets are . Tuples, strings, ints, floats and bools are . A dictionary key or set element must be , so a is allowed but a is not.

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.

Recall: click each blank to check yourself

Fill in the three keywords.

numbers: list[int] = [1, 2, 3, 4, 5, 6]
squares: set[int] = {n * n  n  numbers  n % 2 == 0}
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

  1. Write your own function called unionize for 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.
  1. Write your own function called intersect for 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.
  1. Write your own function called sym_diff for 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.