Python Basics — Sets: Practice Exercises

2 minute read

Sets — Practice Exercises

Test your understanding of set creation, operations, methods, frozensets, and comprehensions.


Exercise 1 — Common and Unique Elements

Given two lists, find: (a) elements common to both, (b) elements unique to each, (c) all unique elements combined.

list1 = [1, 2, 3, 4, 5, 3, 2]
list2 = [4, 5, 6, 7, 8, 5, 6]
Show Solution
list1 = [1, 2, 3, 4, 5, 3, 2]
list2 = [4, 5, 6, 7, 8, 5, 6]

set1 = set(list1)
set2 = set(list2)

# Common elements
common = set1 & set2
print(f"Common: {common}")  # {4, 5}

# Unique to each
only1 = set1 - set2
only2 = set2 - set1
print(f"Only in list1: {only1}")  # {1, 2, 3}
print(f"Only in list2: {only2}")  # {6, 7, 8}

# All unique elements combined
all_unique = set1 | set2
print(f"All unique: {all_unique}")  # {1, 2, 3, 4, 5, 6, 7, 8}

Exercise 2 — Permission Checker

Write a function check_access(required, user_permissions) that:

  • Returns True if user has all required permissions
  • If not, prints which permissions are missing
check_access({"read", "write"}, {"read", "write", "execute"})  # True
check_access({"read", "admin"}, {"read", "write"})  # Missing: {'admin'}
Show Solution
def check_access(required, user_permissions):
    if required <= user_permissions:
        print("Access granted")
        return True
    else:
        missing = required - user_permissions
        print(f"Access denied. Missing: {missing}")
        return False

check_access({"read", "write"}, {"read", "write", "execute"})
# Access granted

check_access({"read", "admin"}, {"read", "write"})
# Access denied. Missing: {'admin'}

check_access(set(), {"read"})
# Access granted (empty set is subset of everything)

Exercise 3 — Remove Duplicates Preserving Order

Write a function unique_ordered(items) that removes duplicates from a list while preserving the original order. Use a set for tracking.

Show Solution
def unique_ordered(items):
    seen = set()
    result = []
    for item in items:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

print(unique_ordered([3, 1, 4, 1, 5, 9, 2, 6, 5, 3]))
# [3, 1, 4, 5, 9, 2, 6]

print(unique_ordered(["b", "a", "c", "a", "b"]))
# ['b', 'a', 'c']

Exercise 4 — Set Comprehension Challenge

Using a set comprehension, find all unique vowels present in a given string (case-insensitive).

find_vowels("Hello World")        # {'e', 'o'}
find_vowels("AEIOU aeiou")        # {'a', 'e', 'i', 'o', 'u'}
find_vowels("rhythm")             # set()
Show Solution
def find_vowels(text):
    vowels = set("aeiou")
    return {ch.lower() for ch in text if ch.lower() in vowels}

print(find_vowels("Hello World"))        # {'e', 'o'}
print(find_vowels("AEIOU aeiou"))        # {'a', 'e', 'i', 'o', 'u'}
print(find_vowels("rhythm"))             # set()
print(find_vowels("Beautiful Day"))      # {'e', 'a', 'u', 'i'}

Exercise 5 — Frozenset as Dict Key

Create a lookup system where frozen sets of ingredients map to recipe names. Then write a function that, given a list of ingredients, finds matching recipes.

Show Solution
recipes = {
    frozenset({"bread", "cheese"}): "Grilled Cheese",
    frozenset({"bread", "cheese", "ham"}): "Ham & Cheese",
    frozenset({"pasta", "sauce", "cheese"}): "Mac & Cheese",
    frozenset({"rice", "beans"}): "Rice & Beans",
}

def find_recipes(ingredients):
    ingredient_set = frozenset(ingredients)
    matches = []
    for recipe_ingredients, name in recipes.items():
        if recipe_ingredients <= ingredient_set:
            matches.append(name)
    return matches

print(find_recipes(["bread", "cheese", "ham", "butter"]))
# ['Grilled Cheese', 'Ham & Cheese']

print(find_recipes(["pasta", "sauce", "cheese"]))
# ['Mac & Cheese']

print(find_recipes(["water"]))
# []

Scoring Guide

Score Level
5/5 Excellent — sets mastered
3-4/5 Good — review operations and frozensets
1-2/5 Keep practicing — re-read the chapter

Next chapter: Functions →

Updated: