Introduction
Sets are unordered collections of unique elements. They are useful for membership testing and eliminating duplicates.
Creating Sets
# Basic set
fruits = {"apple", "banana", "cherry"}
# From list (removes duplicates)
nums = set([1, 2, 2, 3, 3, 3]) # {1, 2, 3}
# Empty set (not {})
empty = set()
Set Operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
# Union
print(a | b) # {1, 2, 3, 4, 5, 6}
print(a.union(b))
# Intersection
print(a & b) # {3, 4}
print(a.intersection(b))
# Difference
print(a - b) # {1, 2}
print(a.difference(b))
# Symmetric difference
print(a ^ b) # {1, 2, 5, 6}
Set Methods
s = {1, 2, 3}
s.add(4) # Add element
s.remove(2) # Remove (raises error if not found)
s.discard(5) # Remove (no error)
s.pop() # Remove and return arbitrary element
s.clear() # Empty the set
Practice Problems
- Find common elements in two lists
- Remove all duplicates from a list
- Check if one set is subset of another
- Find elements in first list but not in second
- Implement set operations for given data