PYTHON
Advanced Set Operations for Data Comparison and Manipulation
Master advanced Python set operations like `difference`, `intersection`, `union`, and `symmetric_difference` to efficiently compare and manipulate collections of unique data.
# Define some sample sets
set_a = {1, 2, 3, 4, 5}
set_b = {4, 5, 6, 7, 8}
set_c = {1, 9, 10}
print(f"Set A: {set_a}")
print(f"Set B: {set_b}")
print(f"Set C: {set_c}
")
# Union: All unique elements from both sets
union_ab = set_a.union(set_b)
print(f"Union of A and B (A | B): {union_ab}") # Output: {1, 2, 3, 4, 5, 6, 7, 8}
# Intersection: Common elements in both sets
intersection_ab = set_a.intersection(set_b)
print(f"Intersection of A and B (A & B): {intersection_ab}") # Output: {4, 5}
# Difference: Elements in A but not in B
difference_ab = set_a.difference(set_b)
print(f"Difference of A and B (A - B): {difference_ab}") # Output: {1, 2, 3}
# Difference: Elements in B but not in A
difference_ba = set_b.difference(set_a)
print(f"Difference of B and A (B - A): {difference_ba}
") # Output: {6, 7, 8}
# Symmetric Difference: Elements in either A or B, but not in both (exclusive OR)
symmetric_difference_ab = set_a.symmetric_difference(set_b)
print(f"Symmetric Difference of A and B (A ^ B): {symmetric_difference_ab}") # Output: {1, 2, 3, 6, 7, 8}
# Subset check: Is set_c a subset of set_a?
is_subset_ca = set_c.issubset(set_a)
print(f"Is C a subset of A? {is_subset_ca}") # Output: False
# Superset check: Is set_a a superset of {1, 2}?
is_superset_a_subset = set_a.issuperset({1, 2})
print(f"Is A a superset of {{1, 2}}? {is_superset_a_subset}") # Output: True
How it works: This snippet demonstrates various powerful set operations in Python, which are highly optimized for efficiency, often performing operations in O(N) time where N is the total number of elements. Sets store only unique elements and are ideal for tasks requiring membership testing, removing duplicates, and comparing collections. The example covers `union` (all unique elements), `intersection` (common elements), `difference` (elements unique to one set), and `symmetric_difference` (elements unique to either set but not both), along with `issubset` and `issuperset` for relationship checks. These operations are critical in data analysis, database operations, and algorithm design.