PYTHON
Perform Efficient Set Operations for Unique Elements
Discover how to use Python sets to manage unique collections of items and perform fast mathematical set operations like union, intersection, difference, and symmetric difference.
# Creating sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set3 = set([3, 5, 7, 9]) # From a list
print(f"Set 1: {set1}")
print(f"Set 2: {set2}")
print(f"Set 3: {set3}")
# Union (all unique elements from both sets)
union_set = set1.union(set2) # or set1 | set2
print(f"Union (set1 | set2): {union_set}")
# Intersection (elements common to both sets)
intersection_set = set1.intersection(set2) # or set1 & set2
print(f"Intersection (set1 & set2): {intersection_set}")
# Difference (elements in set1 but not in set2)
difference_set = set1.difference(set2) # or set1 - set2
print(f"Difference (set1 - set2): {difference_set}")
# Symmetric Difference (elements in either set, but not in both)
symmetric_difference_set = set1.symmetric_difference(set2) # or set1 ^ set2
print(f"Symmetric Difference (set1 ^ set2): {symmetric_difference_set}")
# Check for subsets and supersets
print(f"Is {{1, 2}} a subset of set1? {{1, 2}}.issubset(set1): { {1, 2}.issubset(set1) }")
print(f"Is set1 a superset of {{1, 2}}? set1.issuperset({{1, 2}}): { set1.issuperset({1, 2}) }")
# Adding and removing elements
my_set = {10, 20}
my_set.add(30)
my_set.remove(10) # Raises KeyError if element not present
my_set.discard(20) # Does not raise error if element not present
print(f"Modified set: {my_set}")
How it works: Sets in Python are unordered collections of unique elements, perfect for tasks requiring distinct items or mathematical set operations. They offer highly efficient membership testing and support operations like union (`|`), intersection (`&`), difference (`-`), and symmetric difference (`^`) to combine or compare collections of items. This makes them invaluable for data cleaning and comparison.