TutreNews Learn

Dictionaries and sets

Sets

Goal: Remove duplicates and combine collections with union, intersection and difference · 10 min

A set is an unordered collection of unique items: tags = {"python", "code", "python"} contains just two items. Create an empty set with set() (not {}, which is an empty dictionary).

Uses:

  • Remove duplicates: set([3, 1, 3, 2, 1]) → {1, 2, 3}. The original order is lost; use sorted(set(x)) for a sorted unique list.
  • Fast membership: x in my_set is fast even for millions of items, while a list must be searched one by one.

Changing: add(x), remove(x) (KeyError if absent), discard(x) (no error). Because sets are unordered there is no indexing and no slicing.

Set algebra compares collections:

operatormethodmeaning
`ab`a.union(b)in a or b
a & ba.intersection(b)in both
a - ba.difference(b)in a but not in b
a ^ ba.symmetric_difference(b)in exactly one of them
a <= ba.issubset(b)every item of a is in b

Example: {1, 2, 3} & {2, 3, 4} is {2, 3}. A set comprehension looks like a list comprehension with braces: {len(w) for w in words}.

Because the order of a set is not guaranteed, always sort before printing if you need stable output: print(sorted(s)).

Worked example: Who attended both days?

  1. mon = {"Ada", "Alan", "Grace"}; tue = {"Alan", "Grace", "Linus"}.
  2. Both days: mon & tue = {Alan, Grace}. Only Monday: mon - tue = {Ada}.
  3. Anyone present at least once: mon | tue (4 people).
mon = {"Ada", "Alan", "Grace"}
tue = {"Alan", "Grace", "Linus"}
print(sorted(mon & tue))
print(sorted(mon - tue))
print(len(mon | tue))

Output:

['Alan', 'Grace']
['Ada']
4