Sets: unique items and fast lookups
Why this matters
Two questions come up in almost every program that handles data: "have I seen this before?" and "what's different between these two lists?" Which emails signed up twice, which products vanished from today's stock list, which hikers are on both trips. You can answer them with loops over lists, but Python has a type built for exactly this, the set, and it turns pages of loops into one line that also runs much faster. Sets are a favorite in coding interviews for the same reason.
- Make a set, add and remove items, and explain why it never holds duplicates
- Check membership quickly, and say why a set is faster than a list for it
- Compare collections with union, intersection, difference and subset tests
- Reconcile two lists: what's new, what's gone and what stayed
A collection with no repeats
A set holds items with no duplicates and no order. You write one with curly braces, or build one from any collection with set(). Adding something that's already there changes nothing:
gear = {"tent", "stove", "lantern"}
print(gear, len(gear))
gear.add("stove") # already there: nothing happens
gear.add("rope")
print(gear, len(gear))
signups = ["ana@ex.org", "bo@ex.org", "ana@ex.org", "cy@ex.org", "bo@ex.org"]
print(len(signups), "sign-ups from", len(set(signups)), "people")
Run it a few times, and look at the order the gear prints in. A set doesn't keep the order you added things in, so you can't ask for "item 0": gear[0] is an error. If you need order, sort it on the way out, with sorted(gear), which gives you a list.
One trap catches everyone once: {} is an empty dictionary, not an empty set, because dictionaries had the braces first. An empty set is set().