indusai.co

Sets

A set is an unordered collection of unique values. Use a set when you care about which items are present, not how many times or in what order.

Creating a set

python
colours = {"red", "green", "blue"}
print(colours)

numbers = set([1, 2, 2, 3, 3, 3])
print(numbers)          # duplicates vanish

empty = set()           # {} would create an empty dict
print(type(empty))

Sets can only hold immutable values: numbers, strings, tuples. A list inside a set is an error.

No order, no indexing

You cannot do colours[0]. The order in which items print is not guaranteed and may change between runs.

Adding and removing

python
s = {1, 2}
s.add(3)
s.update([4, 5, 5])
print(s)

s.remove(1)      # KeyError if missing
s.discard(99)    # silently ignores missing
print(s)

item = s.pop()   # removes an arbitrary item
print(item, s)

Membership is fast

Checking whether a value is in a set takes the same time no matter how big the set is. For a list the time grows with its length. When you check membership repeatedly, convert to a set first.

python
blocked = {"spam@x.com", "bot@y.com"}
print("spam@x.com" in blocked)

Set operations

This is where sets shine.

python
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)   # union: in either
print(a & b)   # intersection: in both
print(a - b)   # difference: in a but not b
print(a ^ b)   # symmetric difference: in exactly one

The same operations exist as methods, which also accept any iterable, not just sets:

python
a = {1, 2, 3}
print(a.union([3, 4]))
print(a.intersection([2, 3, 9]))
print(a.difference([1]))

Subsets and supersets

python
small = {1, 2}
big = {1, 2, 3}
print(small.issubset(big))
print(big.issuperset(small))
print(small.isdisjoint({9}))

Removing duplicates while keeping order

A set loses order. If you need unique items in their original order, use dict.fromkeys, which keeps insertion order:

python
items = ["b", "a", "b", "c", "a"]
print(list(dict.fromkeys(items)))

Set comprehensions

python
lengths = {len(w) for w in ["hi", "hello", "hey", "yo"]}
print(lengths)

frozenset

An immutable set. It can be used as a dictionary key or as a member of another set.

python
fs = frozenset([1, 2, 3])
print(fs)

Practice

  1. Two students list their favourite subjects. Find the subjects they have in common and the subjects only the first student likes.
  2. Count how many unique words appear in "the cat and the hat and the bat".
  3. Check whether every letter of "aeiou" appears in "education" using a subset test.