What are the common set operations in Python, and what is a frozenset?
Sets support union (|), intersection (&), difference (-) and symmetric difference (^). A set holds unique, hashable items with fast membership tests. A frozenset is an immutable set, so it can be a dict key or a set element.
Explain it simply
Two WhatsApp groups, "Class A" and "Class B". Union is everyone in either group. Intersection is people in both. Difference is people only in A. Symmetric difference is people in exactly one of them. A set never lists a person twice.
Example
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a | b) # Output: {1, 2, 3, 4, 5}
print(a & b) # Output: {3, 4}
print(a - b) # Output: {1, 2}
print(a ^ b) # Output: {1, 2, 5}
print(a.issubset({1, 2, 3, 4, 5})) # Output: True
fs = frozenset([1, 2])
registry = {fs: "pair"}
print(registry[frozenset([2, 1])]) # Output: pairSet membership (x in s) is O(1) on average, compared with O(n) for a list. Sets are unordered, so do not rely on printing order for larger or non-integer sets.
What to say in the interview
"Sets are unordered collections of unique hashable items. The main operations are union, intersection, difference and symmetric difference, available as operators and methods. Membership is average O(1). A frozenset is the immutable version, so it is hashable and can sit inside another set or be a dictionary key."
Common mistakes
- Writing
{}for an empty set; that is an empty dict.