Python Sets · Exercises
Beginner

Python Sets Exercises

4 exercises that build on the Python Sets lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A set is an unordered collection of unique values: adding a value that is already there changes nothing, and checking whether a value is in the set is very fast. By the end you can create sets, remove duplicates from a list, add and remove items, test membership, and combine sets with union, intersection and difference. You will practise: Count unique visitors; Predict the set operations; Fix the shared hobbies; Find the duplicated order IDs.

0 / 4 completed

Python Sets practice exercises

1. Count unique visitors

Write code Easy

visitor_ids contains one ID per page visit, so the same visitor can appear several times. Store the number of different visitors in unique_count and print it.

Your code
visitor_ids = [101, 205, 101, 330, 205, 101, 412]
unique_count = 0

# your code here

2. Predict the set operations

Predict the output Medium

Read the code and type exactly what it will print. Then press Check to run it and compare.

Read this code
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a & b)
print(sorted(a - b))
print(len(a | b))
a.add(2)
print(len(a))

3. Fix the shared hobbies

Fix the bug Medium

shared should hold only the hobbies that Ana and Ben both have, so the program should print Shared: ['chess', 'hiking']. Instead it prints every hobby. Fix the bug.

Your code
ana = ["chess", "music", "hiking", "music"]
ben = ["hiking", "games", "chess"]
shared = set(ana) | set(ben)
print("Shared:", sorted(shared))

4. Find the duplicated order IDs

Write code Hard

Some orders were submitted twice. Loop over order_ids once and use the two sets provided: add every ID to seen, and if an ID is already in seen when you reach it, add it to duplicates. The final line prints the duplicates in sorted order.

Your code
order_ids = [5012, 5013, 5012, 5020, 5013, 5012, 5031]
seen = set()
duplicates = set()

# loop over order_ids here

print(sorted(duplicates))

Next lessonPython Set Operations

More Python Sets examples · All Python exercises