What they are
A set is a collection of unique items with no duplicates. Sets are unordered (no index positions) and mutable (you can add/remove items).
Creating sets
# Create a set:
numbers = {1, 2, 3, 4, 5}
# From a list (removes duplicates):
my_list = [1, 2, 2, 3, 3, 3]
unique = set(my_list) # {1, 2, 3}
# Empty set (note: use set(), not {})
empty = set() # Correct
# empty = {} # Wrong! This creates a dict
Adding and removing
numbers = {1, 2, 3}
# Add one item:
numbers.add(4) # {1, 2, 3, 4}
# Add multiple:
numbers.update([5, 6]) # {1, 2, 3, 4, 5, 6}
# Remove:
numbers.remove(3) # {1, 2, 4, 5, 6}
# numbers.remove(99) # KeyError if not found
# Safe remove:
numbers.discard(99) # No error if not found
Set operations
Sets are great for mathematical operations:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# Union (all items from both):
union = set1 | set2 # {1, 2, 3, 4, 5, 6}
# Intersection (items in both):
intersection = set1 & set2 # {3, 4}
# Difference (items in set1 but not set2):
difference = set1 - set2 # {1, 2}
# Check membership:
if 3 in set1:
print("Found")
When to use sets
- Removing duplicates from a list
- Fast membership testing (
inis very fast) - Finding common/uncommon items between collections
- When order doesn't matter and you need uniqueness