Python sets are not just great for storing unique elements—they also allow you to perform powerful mathematical set operations such as union, intersection, and difference. These operations are useful for comparing datasets, finding common or distinct values, and filtering elements.
In this post, you’ll learn how to use these operations with simple examples and clear explanations.
1. What Are Set Operations?
Set operations help you combine or compare two or more sets. Python provides built-in methods and operators to perform the following key operations:
- Union (
|
orunion()
): Combines all unique elements from both sets - Intersection (
&
orintersection()
): Returns only the elements present in both sets - Difference (
-
ordifference()
): Returns elements present in the first set but not in the second
2. Union of Sets
The union operation combines elements from two sets, removing duplicates.
# Example 1: Using | operator
A = {1, 2, 3}
B = {3, 4, 5}
print(A | B) # Output: {1, 2, 3, 4, 5}
# Example 2: Using union() method
print(A.union(B)) # Output: {1, 2, 3, 4, 5}
3. Intersection of Sets
The intersection operation returns the common elements from both sets.
# Example 3: Using & operator
A = {10, 20, 30}
B = {20, 30, 40}
print(A & B) # Output: {20, 30}
# Example 4: Using intersection() method
print(A.intersection(B)) # Output: {20, 30}
4. Difference of Sets
The difference operation returns elements that are in the first set but not in the second.
# Example 5: Using - operator
A = {1, 2, 3, 4}
B = {3, 4, 5}
print(A - B) # Output: {1, 2}
# Example 6: Using difference() method
print(B.difference(A)) # Output: {5}
5. Chaining Set Operations
You can also combine operations to perform more complex comparisons.
# Example 7: Chained operations
A = {1, 2, 3, 4}
B = {3, 4, 5}
C = {4, 5, 6}
result = A.union(B).intersection(C)
print(result) # Output: {4}
6. Set Operation Shortcuts
Operation | Operator | Method |
---|---|---|
Union | | |
union() |
Intersection | & |
intersection() |
Difference | - |
difference() |
When to Use Set Operations
- Union: Combine data without duplication
- Intersection: Find common values between datasets
- Difference: Filter out elements found in another set
Summary
- union() or
|
: Combines elements from both sets - intersection() or
&
: Returns only shared elements - difference() or
-
: Filters out elements from the second set
Final Thoughts
Set operations in Python are a simple yet powerful way to compare and manipulate collections of data. They allow for efficient, readable, and flexible code—whether you're working with user inputs, datasets, or any collection of unique elements.