Sets
Unique values and operations on collections.
A set stores only unique values and does not guarantee any order. It is written in curly braces without pairs: {1, 2, 3}. Duplicates disappear by themselves: set([1, 1, 2]) gives {1, 2}. This is the shortest way to remove duplicates: list(set(items)). The order is lost along the way, though.
An empty set can only be set(): writing {} creates an empty dictionary.
The check x in s on a set is instant even with a million elements. On a list Python goes through the elements one by one. If a loop keeps asking "is this value there", turn the list into a set first.
Methods: add(x) adds an element, discard(x) removes it without an error if it is missing, while remove(x) raises KeyError in that case.
Operations on sets are the same as in school maths:
a = {1, 2, 3}
b = {2, 3, 4}
print(a | b) # {1, 2, 3, 4}
print(a & b) # {2, 3}
print(a - b) # {1}
print(a ^ b) # {1, 4}
Union, intersection, difference and symmetric difference solve tasks like "which products are in both shops" or "who signed up but did not come" in a single line. Only immutable values can be elements of a set: numbers, strings, tuples.
Practice
The length of a set
What does the program print?
print(len({1, 2, 2, 3}))Empty braces
What does {} create in Python?
- An empty dictionary
- An empty set
- An empty list
- An error
Common elements
Write a function common(a, b) that returns a sorted list of the values present in both lists, without duplicates.