Python Set Methods
Master set methods for working with unique collections
๐ฏ Understanding Sets
Sets store unique items with no duplicates. Perfect for removing duplicates and mathematical operations.
# Basic set creation
colors = {"red", "blue", "green"}
numbers = {1, 2, 3, 3, 2} # Duplicates removed
print(numbers) # {1, 2, 3}
Set Methods Overview
Sets have many useful methods for managing unique collections:
Adding Items
Add single or multiple items
Removing Items
Remove items safely or forcefully
Set Operations
Mathematical set operations
Utility Methods
Clear, copy, and check sets
๐น Adding Items
Add single items or multiple items to sets
# add() - Add one item
fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits) # {'apple', 'banana', 'cherry'}
# update() - Add multiple items
fruits.update(["orange", "grape"])
print(fruits) # {'apple', 'banana', 'cherry', 'orange', 'grape'}
# Add from another set
more_fruits = {"kiwi", "mango"}
fruits.update(more_fruits)
print(fruits)
๐น Removing Items
Different ways to remove items from sets
# remove() - Removes item (error if not found)
colors = {"red", "blue", "green"}
colors.remove("blue")
print(colors) # {'red', 'green'}
# discard() - Removes item (no error if not found)
colors.discard("yellow") # No error
colors.discard("red")
print(colors) # {'green'}
# pop() - Removes random item
numbers = {1, 2, 3, 4, 5}
removed = numbers.pop()
print(f"Removed: {removed}")
print(numbers)
# clear() - Remove all items
numbers.clear()
print(numbers) # set()
๐น Set Operations
Mathematical operations between sets
# union() - Combine sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}
combined = set1.union(set2)
print(combined) # {1, 2, 3, 4, 5}
# intersection() - Common items
common = set1.intersection(set2)
print(common) # {3}
# difference() - Items in first but not second
diff = set1.difference(set2)
print(diff) # {1, 2}
# symmetric_difference() - Items in either but not both
sym_diff = set1.symmetric_difference(set2)
print(sym_diff) # {1, 2, 4, 5}
๐น Checking Sets
Check relationships between sets
# issubset() - Check if all items are in another set
small = {1, 2}
big = {1, 2, 3, 4}
print(small.issubset(big)) # True
# issuperset() - Check if contains all items of another
print(big.issuperset(small)) # True
# isdisjoint() - Check if no common items
set_a = {1, 2, 3}
set_b = {4, 5, 6}
print(set_a.isdisjoint(set_b)) # True
# Check membership
print(2 in set_a) # True
print(7 in set_a) # False
๐น Practical Examples
Real-world uses of set methods
# Remove duplicates from list
numbers = [1, 2, 2, 3, 3, 4]
unique = list(set(numbers))
print(unique) # [1, 2, 3, 4]
# Find common interests
alice_hobbies = {"reading", "swimming", "coding"}
bob_hobbies = {"swimming", "gaming", "coding"}
common = alice_hobbies.intersection(bob_hobbies)
print(common) # {'swimming', 'coding'}
# Track unique visitors
visitors = set()
visitors.add("user123")
visitors.add("user456")
visitors.add("user123") # Duplicate ignored
print(len(visitors)) # 2