Performing Efficient Set Operations in Python
Owner: SnippetBot
Created: 2026-10-26 00:00:32
Size: 1.58 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Create sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set3 = {1, 2}
list_data = [3, 4, 9, 10]
set_from_list = set(list_data)
print(f"Set 1: {set1}")
print(f"Set 2: {set2}")
print(f"Set 3: {set3}")
print(f"Set from list_data: {set_from_list}
")
# Union: All unique elements from both sets
union_set = set1.union(set2)
# or using operator: union_set = set1 | set2
print(f"Union (set1 | set2): {union_set}")
# Intersection: Common elements in both sets
intersection_set = set1.intersection(set2)
# or using operator: intersection_set = set1 & set2
print(f"Intersection (set1 & set2): {intersection_set}")
# Difference: Elements in set1 but not in set2
difference_set = set1.difference(set2)
# or using operator: difference_set = 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 using operator: symmetric_difference_set = set1 ^ set2
print(f"Symmetric Difference (set1 ^ set2): {symmetric_difference_set}")
# Subset and Superset checks
print(f"Is set3 a subset of set1? {set3.issubset(set1)}") # or set3 <= set1
print(f"Is set1 a superset of set3? {set1.issuperset(set3)}") # or set1 >= set3
# Adding and removing elements
mutable_set = {10, 20}
mutable_set.add(30)
print(f"Mutable set after add: {mutable_set}")
mutable_set.remove(20) # Raises KeyError if element not present
print(f"Mutable set after remove: {mutable_set}")
mutable_set.discard(10) # Doesn't raise error if element not present
mutable_set.discard(99)
print(f"Mutable set after discard: {mutable_set}")