Skip to content
Codewilds

Lesson 20 of 34 · Dictionaries & Sets

Python Sets and Set Operations

medium20 XP3 min read

A set is an unordered collection of unique items. Sets answer questions like "have I seen this before?" or "which players are in both guilds?" faster and more clearly than lists ever could. If you remember Venn diagrams from school, you already know the operations.

Creating sets

Write a set with curly braces, or convert any iterable with set() — duplicates disappear automatically:

elements = {"fire", "ice", "storm"}
rolls = set([3, 6, 3, 1, 6])
print(rolls)            # {1, 3, 6}
print(set("hollow"))    # {'h', 'o', 'l', 'w'}  (order may vary)
empty = set()           # NOT {} — that's an empty dict!

Adding, removing and checking

seen = {"Ada"}
seen.add("Bo")
seen.add("Ada")          # already there, nothing happens
print(len(seen))         # 2
print("Bo" in seen)      # True

seen.remove("Bo")        # KeyError if the item is missing
seen.discard("Zed")      # no error if the item is missing

Why sets are fast

To check x in some_list, Python compares x with every item, one by one. A set uses a hash table — the same trick as dictionary keys — so x in some_set takes about the same time whether the set holds ten items or ten million. Whenever you repeatedly check membership, use a set.

Set operations

warriors = {"Ada", "Bo", "Cy"}
mages = {"Cy", "Di"}

print(warriors | mages)   # union: in either        {'Ada', 'Bo', 'Cy', 'Di'}
print(warriors & mages)   # intersection: in both   {'Cy'}
print(warriors - mages)   # difference: only left   {'Ada', 'Bo'}
print(warriors ^ mages)   # symmetric difference: in exactly one  {'Ada', 'Bo', 'Di'}

Each operator has a method form — union(), intersection(), difference(), symmetric_difference() — which also accepts lists and other iterables: warriors.union(["Eve"]).

Sets can also be compared:

print({"Cy"} <= warriors)            # True: subset
print(warriors.isdisjoint({"Zed"}))  # True: nothing in common

Sets have no order

Sets don't keep items in any particular order, and they don't support indexing: warriors[0] raises TypeError. When you need a predictable order — for display or for tests — convert with sorted(my_set), which returns a sorted list.

Only hashable items

Like dictionary keys, set items must be immutable: numbers, strings and tuples are fine, lists are not. If you need a set that can itself go inside another set or be used as a dictionary key, use the immutable frozenset.

Common mistakes

  • {} creates a dictionary, not a set. An empty set is set().
  • Expecting order: set([3, 1, 2]) may print in any order. Use sorted() when order matters.
  • remove() on a missing item raises KeyError — use discard() when the item may be absent.
  • Losing order when deduplicating: list(set(items)) removes duplicates but scrambles the order. If order matters, use list(dict.fromkeys(items)), which keeps first occurrences in order.

Assignment

Write three functions using sets:

  1. common_friends(a, b) takes two lists of names and returns an alphabetically sorted list of the names that appear in both. Each name appears only once in the result.
  2. has_duplicates(items) returns True if any item appears more than once, otherwise False.
  3. missing_letters(text) returns an alphabetically sorted list of the lowercase English letters a–z that do not appear in text, ignoring case. A sentence that uses every letter (a pangram) returns [].
common_friends(["Ada", "Bo", "Cy"], ["Cy", "Di", "Ada"])  # ["Ada", "Cy"]
has_duplicates([1, 2, 3, 2])                              # True
missing_letters("The five boxing wizards jump")           # ["c", "k", "l", "q", "y"]

Tip: the standard library's string module has the alphabet ready: after import string, string.ascii_lowercase is "abcdefghijklmnopqrstuvwxyz".

Premium lesson

Unlock the full Learn Python course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Sets in other languages

Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.

Lesson last updated on .

Write code ↓
Python+20 XP

Lesson 20 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn Python course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.