Advanced Set Operations
Set Operation Overview
Common Mathematical Set Operations
| Operation | Method | Description |
| -------------------- | ------------------------------- | ------------------------------------ | ------------------------ |
| Union | |
orunion()
| Combines unique elements |
| Intersection | &
or intersection()
| Common elements |
| Difference | -
or difference()
| Elements in first set not in second |
| Symmetric Difference | ^
or symmetric_difference()
| Elements in either set, but not both |
Practical Set Operation Examples
Union Operation
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
## Union methods
union_set1 = set1 | set2
union_set2 = set1.union(set2)
print(union_set1) ## Output: {1, 2, 3, 4, 5, 6}
Intersection Operation
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
## Intersection methods
intersection_set1 = set1 & set2
intersection_set2 = set1.intersection(set2)
print(intersection_set1) ## Output: {3, 4}
Set Operation Flow
graph TD
A[Set 1] --> B{Set Operation}
C[Set 2] --> B
B --> |Union| D[Combined Unique Elements]
B --> |Intersection| E[Common Elements]
B --> |Difference| F[Unique Elements]
Advanced Set Manipulation
In-place Modification
## Updating sets
numbers = {1, 2, 3}
numbers.update([3, 4, 5])
print(numbers) ## Output: {1, 2, 3, 4, 5}
## Removing elements
numbers.discard(3)
print(numbers) ## Output: {1, 2, 4, 5}
Set Comprehension and Filtering
## Complex set creation
complex_set = {x for x in range(10) if x % 2 == 0}
print(complex_set) ## Output: {0, 2, 4, 6, 8}
- Most set operations have O(min(len(s), len(t))) complexity
- Efficient for large collections
- Ideal for unique element tracking and filtering
With LabEx, you can explore and master these advanced set operations interactively.