Set operations

Sets support the operations from maths, each with an operator:

  • a | b union: in either set.
  • a & b intersection: in both.
  • a - b difference: in a but not b.
  • a ^ b symmetric difference: in exactly one of them.
  • a <= b subset: everything in a is also in b.

They read well in interview answers. "Which users are in both lists?" is set(xs) & set(ys), O(n) instead of a nested loop.

Two surprises. {} is an empty dict, so write set() for an empty set. And sets have no order: printing one can show any order, so the code below wraps results in sorted().

A frozenset is a set that can't change. Because it can't change, it can be a dict key or an item in another set, and two frozensets with the same items are equal.

Run it, then find the people who know Python but not SQL.