Sets: distinct values and comparisons
A set holds each value once. set(items) removes repeats, and intersection, union and difference compare two groups. A set has no order, so sort it before you print it.
- Make a set from a literal or from a list with
set(...), and test membership - Answer group questions with
intersection,unionanddifference - Print a set reliably with
sorted, and remember that{}is an empty dictionary
Some questions are about groups, not individual items: *which customers ordered in both months?*, *which tags do two films share?* A set is a collection of distinct values. A repeated value is kept once, and in on a set is very fast.
Write a set with curly braces and no colons: {"noir", "heist"}. set(items) builds one from a list and drops the repeats. Three methods compare two sets:
a.intersection(b): the values in both.a.union(b): the values in either.a.difference(b): the values inabut not inb.
Run each example to see what it prints. Running examples doesn't count toward progress.
first = {"thriller", "noir", "slow burn", "twist ending"}
second = {"noir", "twist ending", "heist"}
print(sorted(first.intersection(second)))
print(sorted(first.union(second)))
print(sorted(first.difference(second)), sorted(second.difference(first)))
print(len(first), "noir" in first)In data work, sets usually come from lists. An order history repeats customers, so set(customer_ids) gives each customer once. Comparing two months then answers retention questions directly.
january = ["C00164", "C00800", "C04248", "C00800", "C00164"] february = ["C00800", "C01338", "C00800", "C00077"] jan = set(january) feb = set(february) print(len(january), "orders,", len(jan), "customers in January") print("returning:", sorted(jan.intersection(feb))) print("new in February:", sorted(feb.difference(jan))) print("lapsed:", sorted(jan.difference(feb))) print(type({}), type(set()))
When to use it: to remove repeats when order doesn't matter, to test membership in a large group, and to compare two groups. Mistakes to avoid:
- Printing a set and expecting a fixed order.
- Writing
{}for an empty set. - Using a set when you need the first-seen order or the repeats. That is a job for a list.
- A set keeps each value once.
set(items)removes repeats, andinon a set is fast. intersectiongives both,uniongives either, anddifferencegives one but not the other, which depends on the direction.- A set has no order, so print
sorted(s).{}is an empty dictionary andset()is an empty set. - Next: dictionaries and lists inside dictionaries, the shape of real records.