Accel Thinking

Python Learning Notes

What Problems Are Python Sets Best At Solving?

A beginner-friendly Python note on the three jobs sets are best at: O(N) deduplication, O(1) membership checks, and union/intersection/difference — plus how sets, dicts, and lists divide the work.

The list is Python’s most-used container, so many students reach for it even when the task is “check whether something is there” or “remove the duplicates”: a loop with in, plus a second list for dedup. Small data hides the cost; in contest problems, one O(N²) lookup turns an accepted solution into a timeout — the kind that surfaces seconds before the deadline. This note spells out the three jobs sets are genuinely good at — deduplication, fast membership, and set operations — where they fall short, and how sets and dicts divide the work.

The Common Mistake

names = ["amy", "bob", "amy", "cid", "bob"]
unique = []
for name in names:
    if name not in unique:      # scans unique from scratch every time
        unique.append(name)
print(unique)

name not in unique compares against the whole list element by element: deduplicating N items costs 1+2+…+N comparisons, N² in the worst case. A thousand items means about half a million comparisons; a hundred thousand grinds to a halt. Worse, samples often have only a few dozen items, so it runs fine locally and times out on the judge — the bill arrives at the most expensive moment.

The Core Idea

A set is an unordered container of unique values (the 01020 lesson’s definition). Unpack that sentence and you get its three weapons:

  1. Deduplication is built in: throw any sequence into set() and duplicates vanish, O(N).
  2. Membership is O(1): x in s uses hashing, independent of size; a list scans in O(N). In a maze you ask “have I been here?” at every step; set lookups keep the total linear.
  3. Set algebra is built in: union |, intersection &, difference - express “both like”, “only in A” relationships in one line.

Watch a three-step trace: walking a grid with visited = set(); at cell (2,3), check (2,3) in visited — False, step in, add it; later, back at (2,3), check again — True, skip, no infinite loop. Every check is constant time no matter how many cells exist.

And remember the boundaries: a set keeps no order (do not use it when order matters) and holds only immutable elements (no lists or dicts inside; tuples are fine).

Sets vs Dicts: For Counting, Use a Dict

These two hash containers confuse every beginner. The difference is one sentence: a set answers only “is it there?”; a dict also answers “how many?”.

votes = ["amy", "bob", "amy", "amy", "bob", "dan"]

who = set(votes)                 # who voted at all
count = {}
for name in votes:
    count[name] = count.get(name, 0) + 1

print(who)        # {'amy', 'bob', 'dan'}
print(count)      # {'amy': 3, 'bob': 2, 'dan': 1}

Whenever the question says “how many of each”, “which rank”, or “occurrence counts”, the answer is a dict; only “is it there” or “is it new” belongs to a set. The two mistakes are symmetric: counting with a set loses the counts, and membership with a dict drags along a value you never read.

names = ["amy", "bob", "amy", "cid", "bob"]

unique = list(set(names))
print(unique)

a = {"amy", "bob"}
b = {"bob", "dan"}
print(a & b)    # intersection
print(a | b)    # union
print(a - b)    # difference
['amy', 'bob', 'cid']        # set element order is not guaranteed
{'bob'}
{'amy', 'bob', 'dan'}        # same
{'amy'}

One line per job: dedupe with set(names), query with x in s, combine with & | -. Note that a set’s printed order is not guaranteed — compare sets by equality, not by eyeballing order.

Side by Side

Need Recommended Avoid Why
Deduplicate set list loop + in O(N) vs O(N²)
Fast membership set list hash O(1) vs scan O(N)
Count occurrences dict set a set forgets counts
Keep original order list set sets are unordered
Store lists/dicts as elements impossible; use tuples — sets accept immutables only

One line for choosing: “is it there?” → set; “how many?” → dict; “at which position?” → list.

In Real Problems

This exact choice recurs in contests. Walking a maze, record visited cells in a set: one lookup and one add per move, both constant time, no matter how long the path — the visited sets in the CCC 2026 J4 Snail Path walkthrough and the CCC 2020 J5/S2 Escape Room walkthrough are exactly this. Grouping people and answering “which group is this person in” uses a dict for name → group id plus a set for the checks — the core structure of the CCC 2022 J4/S2 Good Groups walkthrough.

Practice

  1. Turn scores = [70, 85, 70, 90, 85] into a deduped list in one line (hint: set ignores order — if order must survive, think of another way).
  2. With two course rosters math = {...} and cs = {...}, write one line listing students taking both.
  3. Challenge: why does {{1, 2}, {3, 4}} raise an error, and how would you store a collection of sets?

One-Sentence Takeaway

Dedup, membership, intersection/union/difference — those three jobs go to sets; for order, counting, or nesting, return to lists and dicts.