Module lessons (4/4)
Sets
A set is a collection of unique, unordered elements. Three superpowers:
- Automatic deduplication: adding the same element twice has no effect.
- O(1) membership test:
x in sis extremely fast even with millions of elements (it's hash-based, like dicts). - Set operations: union, intersection, difference, symmetric difference.
Creating a set
vuoto = set() # ATTENZIONE: {} è un dict vuoto, non un set!
numeri = {1, 2, 3}
da_lista = set([1, 1, 2, 3, 3, 3]) # {1, 2, 3}Braces alone {} create an empty dictionary, not a set: for an empty set
you need set().
Modifying a set
s = {1, 2, 3}
s.add(4) # {1, 2, 3, 4}
s.add(1) # nessun effetto (già presente)
s.discard(99) # rimuove se presente, silenzioso altrimenti
s.remove(2) # rimuove o solleva KeyErrorSet operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a | b # {1, 2, 3, 4, 5, 6} unione
a & b # {3, 4} intersezione
a - b # {1, 2} differenza (in a ma non in b)
a ^ b # {1, 2, 5, 6} differenza simmetrica (xor)There are also method forms (a.union(b), a.intersection(b), …) which in
addition accept any iterable, not only sets.
Membership test
parole = {"ciao", "mondo", "python"}
"ciao" in parole # True O(1)
"java" not in parole # TrueFor comparison: searching with in inside a list is O(n) and on long
lists it is much slower.
Frozen set: the immutable version
frozenset({1, 2, 3}) is the hashable version: it can be a dict key or an
element of another set.
Set operations and performance
Sets are implemented as hash tables, which makes membership testing (x in my_set) extremely fast: it runs in constant time O(1), unlike lists where searching takes linear time O(n). Additionally, they support algebraic operations like union (|), intersection (&), and difference (-).
Try it
Given the list `nums = [1, 2, 2, 3, 3, 3, 4]`, build `unique_items` with the unique values (in any order) and then compute `count` as len(unique_items). Evaluate `count`.
Show hint
set(nums) removes duplicates.
Solution available after 3 attempts
Review exercise
Given `a = {1, 2, 3, 4}` and `b = {3, 4, 5, 6}`, compute the intersection into `common_items` and the difference a-b into `only_a`. Evaluate the tuple `(common_items, only_a)`.
Show hint
& intersection, - difference.
Solution available after 3 attempts
Additional challenge
Given two sets `set_a = {1, 2, 3}` and `set_b = {2, 3, 4}`, calculate the mathematical intersection of the two sets (their common elements). Store the resulting set in `common_elements` and evaluate it.
Show hint
You can use the & operator or the set_a.intersection(set_b) method.
Solution available after 3 attempts