Set Operations
Union, intersection, difference
Interview Relevant: Mathematical operations
Set Operations
Mathematical set operations.
Code Examples
Set mathematical operations.
python
1a = {1, 2, 3, 4}
2b = {3, 4, 5, 6}
3
4# Union (all elements)
5a | b # {1, 2, 3, 4, 5, 6}
6a.union(b)
7
8# Intersection (common elements)
9a & b # {3, 4}
10a.intersection(b)
11
12# Difference (in a but not b)
13a - b # {1, 2}
14a.difference(b)
15
16# Symmetric difference (in either, not both)
17a ^ b # {1, 2, 5, 6}
18a.symmetric_difference(b)
19
20# Subset and superset
21{1, 2} <= {1, 2, 3} # True (subset)
22{1, 2, 3} >= {1, 2} # True (superset)
23{1, 2}.issubset({1, 2, 3})
24{1, 2, 3}.issuperset({1, 2})
25
26# Disjoint (no common elements)
27{1, 2}.isdisjoint({3, 4}) # True