Set Operation Techniques
Advanced Set Manipulation
1. Set Comprehensions
## Creating sets using comprehensions
squared_numbers = {x**2 for x in range(1, 6)}
print(squared_numbers) ## {1, 4, 9, 16, 25}
## Filtered set comprehension
even_squares = {x**2 for x in range(1, 10) if x % 2 == 0}
print(even_squares) ## {4, 16, 36, 64}
Set Operation Flowchart
graph TD
A[Set Operations]
A --> B[Comprehensions]
A --> C[Subset/Superset]
A --> D[Disjoint Sets]
A --> E[Frozen Sets]
2. Subset and Superset Checks
## Checking set relationships
set1 = {1, 2, 3}
set2 = {1, 2}
## Subset check
print(set2.issubset(set1)) ## True
print(set2 <= set1) ## True
## Superset check
print(set1.issuperset(set2)) ## True
print(set1 >= set2) ## True
Key Set Operations
Operation |
Method |
Description |
Subset |
issubset() |
Checks if all elements are in another set |
Superset |
issuperset() |
Checks if contains all elements of another set |
Disjoint |
isdisjoint() |
Checks if sets have no common elements |
3. Disjoint Sets
## Checking for no common elements
set1 = {1, 2, 3}
set2 = {4, 5, 6}
set3 = {3, 4, 5}
print(set1.isdisjoint(set2)) ## True
print(set1.isdisjoint(set3)) ## False
4. Frozen Sets
## Immutable set version
frozen_set = frozenset([1, 2, 3])
try:
frozen_set.add(4) ## Raises AttributeError
except AttributeError:
print("Frozen sets are immutable")
## Can be used as dictionary keys
my_dict = {frozen_set: "example"}
Set Filtering Techniques
## Complex set filtering
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
## Prime number filtering
def is_prime(n):
return n > 1 and all(n % i != 0 for i in range(2, int(n**0.5) + 1))
prime_numbers = {x for x in numbers if is_prime(x)}
print(prime_numbers) ## {2, 3, 5, 7}
- Set operations are highly optimized
- Best for unique element tracking
- Efficient membership testing
- Useful in mathematical and data processing scenarios
Practical Example
## Real-world set operation
users_web = {"alice", "bob", "charlie"}
users_mobile = {"bob", "david", "eve"}
## Unique users across platforms
total_users = users_web.union(users_mobile)
## Users on both platforms
active_users = users_web.intersection(users_mobile)
print("Total Users:", total_users)
print("Active Users:", active_users)
Explore these advanced techniques with LabEx to master Python set operations efficiently.