Advanced Sets
Set operations, frozenset, set comprehensions, and mathematical operations.
Overview
Master advanced set operations.
Set Operations
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# Union (all elements)
print(A | B) # {1, 2, 3, 4, 5, 6, 7, 8}
print(A.union(B))
# Intersection (common elements)
print(A & B) # {4, 5}
print(A.intersection(B))
# Difference (elements in A not in B)
print(A - B) # {1, 2, 3}
print(A.difference(B))
# Symmetric difference (elements in either but not both)
print(A ^ B) # {1, 2, 3, 6, 7, 8}
print(A.symmetric_difference(B))
# Subset and superset
print({1, 2} <= {1, 2, 3}) # True (subset)
print({1, 2, 3} >= {1, 2}) # True (superset)
Frozenset
# Immutable set
fs = frozenset([1, 2, 3, 4, 5])
# Can be used as dictionary key
d = {frozenset([1, 2]): "pair", frozenset([3, 4]): "another pair"}
# Can be element of another set
nested = {frozenset([1, 2]), frozenset([3, 4])}
Set Comprehensions
# Create set from comprehension
squares = {x**2 for x in range(10)}
print(squares) # {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
# Filter with condition
evens = {x for x in range(20) if x % 2 == 0}
print(evens) # {0, 2, 4, 6, 8, 10, 12, 14, 16, 18}
# Transform
words = ["hello", "world", "python"]
unique_chars = {char for word in words for char in word}
print(unique_chars) # {'h', 'e', 'l', 'o', 'w', 'r', 'd', 'p', 'y', 't', 'n'}
Practice
Find common elements between multiple lists using sets.