Warm-up · Activity 1 of 7
// B4.4 · ~25 min · Beginner
Sets
After this lesson you can create sets, including the empty set, test membership, combine sets with their four operators, and use sets to remove duplicates.
Predict · Activity 2 of 7
Predict before you read on: what does this print?
print(len({1, 2, 2, 3, 3, 3}))Practice · Activity 3 of 7
Fill in an empty set, so that add() works on the next line.
empty = ____ empty.add("x")empty =Practice · Activity 4 of 7
sorted() turns each set into a list in order, so the output is predictable. What does this print?
a = {1, 2, 3, 4} b = {3, 4, 5} print(sorted(a & b), sorted(a - b))Practice · Activity 5 of 7
With these two sets, match each expression to its items.
a = {1, 2, 3} b = {3, 4}Brain teaser · Activity 6 of 7
Brain teaser. Three values of three different types. What does this print?
print(len({1, 1.0, True}))Apply · Activity 7 of 7
Mini-task. Write missing_letters(text), which returns, in alphabetical order, the letters a to z that do not appear anywhere in text, ignoring capitals. For "The quick brown fox jumps over the lazy dog" the answer is [], because that sentence uses every letter.
Check your work against this list
Build it yourself
Read the worked example, then write the exercises. Your code runs in your browser or on your computer and is never uploaded.
Worked example
Two course rosters
Two courses collected sign-ups; one person signed up twice for Python. set() drops the duplicate, in answers membership questions, and the four operators compare the two rosters. Every set is passed to sorted() before printing, because a set has no order of its own. At the end, a set comprehension collects each initial once. Add names to either list and run it again.
main.py
python_course = ["ana", "ben", "cleo", "ben", "dan"]
web_course = ["cleo", "eve", "dan", "fay"]
python_set = set(python_course) # the duplicate "ben" disappears
web_set = set(web_course)
print("Python:", len(python_course), "sign-ups,", len(python_set), "people")
print("Is eve in Python?", "eve" in python_set)
print("Both:", sorted(python_set & web_set))
print("Either:", sorted(python_set | web_set))
print("Only Python:", sorted(python_set - web_set))
print("Exactly one:", sorted(python_set ^ web_set))
initials = {name[0].upper() for name in python_set | web_set}
print("Initials:", sorted(initials))
Run it with
python main.pyOutput
Python: 5 sign-ups, 4 people
Is eve in Python? False
Both: ['cleo', 'dan']
Either: ['ana', 'ben', 'cleo', 'dan', 'eve', 'fay']
Only Python: ['ana', 'ben']
Exactly one: ['ana', 'ben', 'eve', 'fay']
Initials: ['A', 'B', 'C', 'D', 'E', 'F']- len(python_course) counts sign-ups; len(python_set) counts people.
- Exactly one (^) is Either minus Both.
- The set comprehension builds each initial once, even though two lists are combined.
Change it and run it
Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.
The first run downloads Python for your browser (up to 6.5 MB) and keeps it cached. Your code stays on your device.
Exercises
Exercise 1 of 2
Each word once
unique_words(text) should return every word of text once, in lower case and in alphabetical order. text.lower().split() already gives the lower-case words as a list. The starter sorts them but keeps the duplicates. Remove them with a set.
Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.
The first run downloads Python for your browser (up to 6.5 MB) and keeps it cached. Your code stays on your device.
Hints
Hint 1
A set keeps each value once. Build one from the words before sorting.
Hint 2
sorted() accepts a set and returns a list.
Hint 3
return sorted({word for word in text.lower().split()}), or sorted(set(text.lower().split()))
Show a solution
One way to solve it. Yours can look different and still pass the checks.
def unique_words(text: str) -> list[str]:
"""Return each word of text once, in lower case and alphabetical order."""
return sorted({word for word in text.lower().split()})
Run it on your computer
Install Python 3.14 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.
main.py
def unique_words(text: str) -> list[str]:
"""Return each word of text once, in lower case and alphabetical order."""
return sorted(text.lower().split())
test_main.py
from main import unique_words
def test_duplicates_removed():
"""Lists each word once"""
got = unique_words("the cat and the hat")
assert got == ["and", "cat", "hat", "the"], f"got {got!r}, expected ['and', 'cat', 'hat', 'the']"
def test_case_ignored():
"""Treats The and the as the same word"""
got = unique_words("The dog saw THE dog")
assert got == ["dog", "saw", "the"], f"got {got!r}, expected ['dog', 'saw', 'the']"
def test_empty_text():
"""Empty text gives an empty list"""
got = unique_words("")
assert got == [], f"unique_words('') returned {got!r}, expected []"
On macOS and Linux, type python3 wherever these commands say python, as in the first lesson.
Run the program:
python main.pyRun the checks (needs learnrun.py in the same folder):
python learnrun.py testDownload learnrun.pyExercise 2 of 2
Compare two lists
compare(mine, yours) gets two lists of names and should return three sorted lists as a tuple: the names on both lists, the names only in mine, and the names only in yours. A name may appear twice in a list, but only once in the result. The starter only builds the union. Use &, - and the right order of operands.
Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.
The first run downloads Python for your browser (up to 6.5 MB) and keeps it cached. Your code stays on your device.
Hints
Hint 1
Turn both lists into sets first: a, b = set(mine), set(yours).
Hint 2
a & b gives the names on both lists. a - b and b - a are not the same.
Hint 3
return sorted(a & b), sorted(a - b), sorted(b - a)
Show a solution
One way to solve it. Yours can look different and still pass the checks.
def compare(mine: list[str], yours: list[str]) -> tuple[list[str], list[str], list[str]]:
"""Return (in both, only in mine, only in yours), each sorted."""
a, b = set(mine), set(yours)
return sorted(a & b), sorted(a - b), sorted(b - a)
Run it on your computer
Install Python 3.14 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.
main.py
def compare(mine: list[str], yours: list[str]) -> tuple[list[str], list[str], list[str]]:
"""Return (in both, only in mine, only in yours), each sorted."""
everyone = set(mine) | set(yours)
return sorted(everyone), [], []
test_main.py
from main import compare
def test_both():
"""The first list holds the names on both lists"""
both, _, _ = compare(["ana", "ben", "cleo"], ["ben", "dan", "ana"])
assert both == ["ana", "ben"], f"in both: got {both!r}, expected ['ana', 'ben']"
def test_only_one_side():
"""The second and third lists hold the names on one list only"""
_, only_mine, only_yours = compare(["ana", "ben", "cleo"], ["ben", "dan", "ana"])
assert (only_mine, only_yours) == (["cleo"], ["dan"]), f"got {(only_mine, only_yours)!r}, expected (['cleo'], ['dan'])"
def test_duplicates():
"""A name listed twice appears once"""
got = compare(["eve", "eve"], ["eve"])
assert got == (["eve"], [], []), f"got {got!r}, expected (['eve'], [], [])"
On macOS and Linux, type python3 wherever these commands say python, as in the first lesson.
Run the program:
python main.pyRun the checks (needs learnrun.py in the same folder):
python learnrun.py testDownload learnrun.pyCommon mistakes
Starting an empty set with {}
seen = {}
seen.add("ana")
What Python prints
AttributeError: 'dict' object has no attribute 'add'Why, and the fix
{} is an empty dict, not an empty set, and a dict has no add() method. Write seen = set() for an empty set. Braces with values, such as {"ana"}, do make a set.
Putting a list into a set
pairs = {[1, 2], [3, 4]}
What Python prints
TypeError: cannot use 'list' as a set element (unhashable type: 'list')Why, and the fix
Set items must be hashable, and a list is not, because it can change. Use tuples for the inner values: {(1, 2), (3, 4)}.
Indexing a set
colours = {"red", "green"}
print(colours[0])
What Python prints
TypeError: 'set' object is not subscriptableWhy, and the fix
A set has no positions, so there is no first item. Loop over it, test with in, or turn it into a sorted list first: sorted(colours)[0].
Python in the browser: Pyodide 314.0.7, MPL-2.0. Licence and source
Exit ticket
5 questions, no hints. Score 80% or more to complete the lesson.
Finish every activity above to unlock the exit ticket.