Python Sets 🎱
What is a Set?
A set is a collection which is unordered, unchangeable*, and unindexed. Sets do not allow duplicate values.
* Note: Set items are unchangeable, but you can remove items and add new items.
🔮 Analogy: Bag of Marbles
Think of a set as a bag of marbles.
- When you reach in, you don't know which one you'll grab first (Unordered).
- You can't say "give me the 3rd marble" because they are jumbled up (Unindexed).
- If you try to put an identical marble in, it magically vanishes. Only unique marbles allowed! (No Duplicates).
✨ Creating and Accessing
thisset = {"apple", "banana", "cherry"}
print(thisset)
# Check if item exists (Fast O(1) lookup!)
print("banana" in thisset) # True🔗 Set Operations
Sets are powerful because they support mathematical operations like union, intersection, difference, and symmetric difference.
Union (|)
Combines all items from both sets.
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = set1 | set2
# {'a', 1, 2, 'b', 'c', 3}Intersection (&)
Keeps only items present in BOTH sets.
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1 & set2
# {'apple'}Difference (-)
Keeps items in set1 that are NOT in set2.
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1 - set2
# {'banana', 'cherry'}Symmetric Difference (^)
Keeps items in either set, but NOT in both.
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1 ^ set2
# {'google', 'microsoft', 'banana', 'cherry'}🎯 Real-World Application: Removing Duplicates
The fastest way to remove duplicates from a list is to convert it to a set and back!
emails = ["a@b.com", "c@d.com", "a@b.com"]
unique_emails = list(set(emails))
print(unique_emails) # ['a@b.com', 'c@d.com']💡 Did You Know? Frozenset
Python has a built-in type called frozenset, which is exactly like a set, except that it is immutable (unchangeable).
x = frozenset(["apple", "banana", "cherry"])
x.add("orange") # AttributeError: 'frozenset' object has no attribute 'add'