Sets and Unique Collections
Overview
Sets automatically remove duplicates and allow for fast membership testing, making them perfect for unique collections. You'll learn how to perform set operations such as union, intersection, and difference for comparing data, enabling you to solve problems involving unique values and set mathematics.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- What sets are: Understand how sets store unique, unordered items.
- Creating sets: Learn how to create and modify sets.
- Set operations: Discover union, intersection, and difference operations.
- When to use sets: Understand when sets are better than lists.
Why This Matters
Sets automatically ensure all items are unique - no duplicates allowed! This makes them perfect for situations where you need to eliminate duplicates from a list, check if something exists (membership testing), or perform mathematical set operations. Sets are also optimized for fast lookups, making them very efficient for checking membership!
Step 1: What Is a Set?
A set is an unordered collection of unique items. Unlike lists, sets don't allow duplicates and don't maintain order:
# Create a set with curly braces
fruits = {"apple", "banana", "orange"}
# Create set from a list (removes duplicates)
numbers = set([1, 2, 2, 3, 3, 3])
print(numbers) # Output: {1, 2, 3} (duplicates removed!)
# Empty set (must use set(), not {})
empty = set()
Curly Braces
Sets use curly braces {}, but unlike dictionaries, they contain individual values, not key-value pairs. To create an empty set, you must use set() because {} creates an empty dictionary!
No Duplicates
Sets automatically remove duplicates. If you try to add the same item twice, it only appears once in the set!
Unordered
Sets don't maintain the order of items. When you print a set, items might appear in a different order than you added them!
Key Concept: Sets are perfect for storing unique values. If you have a list with duplicates and need to remove them, convert it to a set! Sets also provide fast membership testing - checking if an item is in a set is very fast, even with large sets!
Mini Practice #1: Creating Sets
Try It YourselfTry creating sets and see how duplicates are removed:
What happened? Sets automatically removed duplicates! Notice how the list [1, 2, 2, 3, 3, 3, 4] became {1, 2, 3, 4} - all duplicates were removed. This is one of the most useful features of sets - converting a list to a set is the easiest way to remove duplicates!
Step 2: Adding and Removing Items
Use add() to add items and remove() or discard() to remove them:
fruits = {"apple", "banana"}
# Add an item
fruits.add("orange")
print(fruits) # Output: {'apple', 'banana', 'orange'}
# Remove an item
fruits.remove("banana")
print(fruits) # Output: {'apple', 'orange'}
# Discard (doesn't error if item doesn't exist)
fruits.discard("grape") # Safe - no error if "grape" doesn't exist
How It Works
The add() method adds a single item to the set. remove() removes an item and raises an error if it doesn't exist. discard() also removes an item but doesn't raise an error if the item doesn't exist - it's safer to use when you're not sure if the item is in the set!
Step 3: Set Operations
Sets support mathematical operations like union, intersection, and difference:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# Union (all items from both sets)
union = set1 | set2 # or set1.union(set2)
print(union) # Output: {1, 2, 3, 4, 5, 6}
# Intersection (items in both sets)
intersection = set1 & set2 # or set1.intersection(set2)
print(intersection) # Output: {3, 4}
# Difference (items in set1 but not in set2)
difference = set1 - set2 # or set1.difference(set2)
print(difference) # Output: {1, 2}
Union
Union combines all items from both sets, removing duplicates. Use | or union() method.
Intersection
Intersection gives you items that appear in both sets. Use & or intersection() method.
Difference
Difference gives you items in the first set but not in the second. Use - or difference() method.
Mini Practice #2: Set Operations
Try It YourselfTry performing set operations:
What happened? You used set operations to find common elements (intersection) and combine sets (union). The intersection found "Bob" who is in both sets. The union combined all students from both sets, automatically removing duplicates. Set operations are powerful for comparing and combining collections!
Step 4: Checking Membership
Sets are optimized for fast membership testing:
fruits = {"apple", "banana", "orange"}
# Check if item is in set
if "apple" in fruits:
print("Apple is in the set!")
# Fast membership test
print("banana" in fruits) # Output: True
print("grape" in fruits) # Output: False
Remember: Checking if an item is in a set is very fast, even with large sets. This makes sets perfect for membership testing. Use the in keyword to check membership!
End-of-Lesson Exercises
Exercise 1: Create and Modify a Set
Create a set called colors with values {"red", "green", "blue"}. Add "yellow" to the set, then remove "green". Print the final set.
Use add() to add items and remove() to remove items.
Exercise 2: Set Operations
Create two sets: set1 = {1, 2, 3, 4} and set2 = {3, 4, 5, 6}. Find and print the intersection (common items) and the union (all items) of both sets.
Use & for intersection and | for union.