What is a Set?
A set is an unordered collection of unique elements. Sets are mutable (you can add/remove items), but they cannot contain duplicate values. Sets are useful for membership testing and eliminating duplicates.
Creating Sets
Create sets using curly braces or the set() constructor:
# Using curly braces
fruits = {"apple", "banana", "orange"}
numbers = {1, 2, 3, 4, 5}
# Empty set (must use set(), not {})
empty = set() # Correct
# empty = {} # This creates a dictionary!
# From list (removes duplicates)
unique_numbers = set([1, 2, 2, 3, 3, 4]) # {1, 2, 3, 4}
# From string
unique_chars = set("hello") # {'h', 'e', 'l', 'o'}
Set Characteristics
- Unordered: No guaranteed order
- Unique: No duplicate values
- Mutable: Can add/remove items
- Unhashable items only: Cannot contain lists or dictionaries
Adding and Removing Items
Adding Items
fruits = {"apple", "banana"}
# Add single item
fruits.add("orange") # {"apple", "banana", "orange"}
# Add multiple items
fruits.update(["grape", "mango"]) # Adds both items
# Add from another set
more_fruits = {"kiwi", "pear"}
fruits.update(more_fruits)
Removing Items
fruits = {"apple", "banana", "orange"}
# Remove item (raises error if not found)
fruits.remove("banana") # {"apple", "orange"}
# Discard item (no error if not found)
fruits.discard("grape") # No error, even if not in set
# Remove and return arbitrary item
item = fruits.pop() # Removes and returns one item
# Clear all items
fruits.clear() # set()
Set Operations
Union (| or union())
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1 | set2 # {1, 2, 3, 4, 5}
union = set1.union(set2) # Same result
Intersection (& or intersection())
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection = set1 & set2 # {3}
intersection = set1.intersection(set2)
Difference (- or difference())
set1 = {1, 2, 3}
set2 = {3, 4, 5}
diff = set1 - set2 # {1, 2} (in set1, not in set2)
diff = set1.difference(set2)
Symmetric Difference (^ or symmetric_difference())
set1 = {1, 2, 3}
set2 = {3, 4, 5}
sym_diff = set1 ^ set2 # {1, 2, 4, 5} (in one, not both)
sym_diff = set1.symmetric_difference(set2)
Set Methods
Common set methods:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
# Check if subset
set1.issubset(set2) # False
{2, 3}.issubset(set1) # True
# Check if superset
set1.issuperset({2, 3}) # True
# Check if disjoint (no common elements)
set1.isdisjoint({4, 5}) # True
# Get length
len(set1) # 3
# Check membership
2 in set1 # True
5 not in set1 # True
Common Use Cases
Remove Duplicates
numbers = [1, 2, 2, 3, 3, 4, 5, 5]
unique = list(set(numbers)) # [1, 2, 3, 4, 5]
# Note: Order may change!
Fast Membership Testing
# Sets are O(1) for membership testing
fruits = {"apple", "banana", "orange"}
if "apple" in fruits: # Very fast!
print("Found!")
# Lists are O(n) - slower for large lists
fruits_list = ["apple", "banana", "orange"]
if "apple" in fruits_list: # Slower for large lists
print("Found!")
Find Common Elements
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
common = set(list1) & set(list2) # {4, 5}
Frozen Sets
Immutable sets (cannot be modified):
# Create frozen set
frozen = frozenset([1, 2, 3])
# Can use in set operations
set1 = {1, 2, 3}
result = set1 | frozen # {1, 2, 3}
# Cannot modify
# frozen.add(4) # AttributeError!
Set Comprehensions
Create sets using comprehensions:
# Set of squares
squares = {x**2 for x in range(5)} # {0, 1, 4, 9, 16}
# Set with condition
evens = {x for x in range(10) if x % 2 == 0} # {0, 2, 4, 6, 8}
Sets vs Lists vs Tuples
| Feature | Set | List | Tuple |
|---|---|---|---|
| Ordered | No | Yes | Yes |
| Mutable | Yes | Yes | No |
| Duplicates | No | Yes | Yes |
| Membership Test | O(1) - Fast | O(n) - Slow | O(n) - Slow |
Best Practices
- Use sets for uniqueness: When you need unique values
- Use sets for fast lookups: Membership testing is very fast
- Use sets for set operations: Union, intersection, difference
- Don't rely on order: Sets are unordered
- Use frozen sets for immutability: When you need an immutable set
Next Steps
Compare with lists and tuples to understand when to use each data structure.