Member-only story
17 Essential Ways to Utilize Python’s Set Data Structure
3 min readSep 15, 2024
1. Creating a Set:
my_set = {1, 2, 3}
empty_set = set()
print("Set created:", my_set, "Empty set:", empty_set)
Set created: {1, 2, 3} Empty set: set()
2. Adding Elements to a Set:
my_set.add(4)
print("After adding 4:", my_set)
After adding 4: {1, 2, 3, 4}
3. Removing Elements from a Set:
# Using remove (raises KeyError if not found):
my_set.remove(2)
print("After removing 2:", my_set)
# Using discard (no error if not found):
my_set.discard(5) # 5 is not in the set, but no error raised
print("After discarding 5 (no change if not found):", my_set)
After removing 2: {1, 3, 4}
After discarding 5 (no change if not found): {1, 3, 4}
4. Set Union: Combines elements of two sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print("Union of set1 and set2:", union_set)
Union of set1 and set2: {1, 2, 3, 4, 5}