Python Basics — Sets
Chapter 12 — Sets
Sets are unordered collections of unique elements. They excel at deduplication, membership testing, and mathematical set operations (union, intersection, difference).
What You’ll Learn
| Topic | Page |
|---|---|
| Creating Sets | Creating Sets → |
| Set Operations | Set Operations → |
| Set Methods | Set Methods → |
| Frozenset | Frozenset → |
| Set Comprehensions | Set Comprehensions → |
| Practice Exercises | Practice Exercises → |
Quick Preview
# Creating sets
fruits = {"apple", "banana", "cherry"}
numbers = {1, 2, 3, 2, 1} # duplicates removed
print(numbers) # {1, 2, 3}
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a & b) # {3, 4} — intersection
print(a | b) # {1, 2, 3, 4, 5, 6} — union
print(a - b) # {1, 2} — difference
Key Properties
| Property | Description |
|---|---|
| Unordered | No index, no guaranteed order |
| Unique | No duplicate elements |
| Mutable | Can add/remove elements |
| Elements | Must be hashable (immutable types) |
| Fast | O(1) membership testing |