SwadhyAI Notes

All Python notes

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

python
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.

python
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.

python
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1 & set2
# {'apple'}

Difference (-)

Keeps items in set1 that are NOT in set2.

python
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1 - set2
# {'banana', 'cherry'}

Symmetric Difference (^)

Keeps items in either set, but NOT in both.

python
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!

python
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).

python
x = frozenset(["apple", "banana", "cherry"])
x.add("orange") # AttributeError: 'frozenset' object has no attribute 'add'