๐ญ Python Set Operations: The Magic of Mixing & Matching
Imagine you have two toy boxes. Set operations are like cool tricks to combine, compare, and find special toys between them!
๐ The Story Begins
Meet Sam and Alex. They each have a box of colored marbles.
- Samโs box: ๐ด Red, ๐ต Blue, ๐ข Green
- Alexโs box: ๐ต Blue, ๐ก Yellow, ๐ข Green
Today, theyโll learn 6 magical tricks to play with their marble collections!
1๏ธโฃ Set Union: โLetโs Put EVERYTHING Together!โ
The Big Idea: Union means all marbles from both boxes โ but no duplicates!
Think of it like a big party. Everyone from both boxes comes. But if Blue is in both? He only comes once!
sam = {"red", "blue", "green"}
alex = {"blue", "yellow", "green"}
# Union: ALL unique marbles
all_marbles = sam | alex
# OR use .union()
all_marbles = sam.union(alex)
print(all_marbles)
# {'red', 'blue', 'green', 'yellow'}
๐จ Visual
graph TD A["Sam's Box] --> C[๐ด ๐ต ๐ข] B[Alex's Box"] --> D["๐ต ๐ก ๐ข"] C --> E["UNION"] D --> E E --> F["๐ด ๐ต ๐ข ๐ก"]
Remember: | or .union() = Everyoneโs invited!
2๏ธโฃ Set Intersection: โWhat Do We BOTH Have?โ
The Big Idea: Intersection finds marbles that appear in both boxes.
Like finding twins! Only marbles that Sam AND Alex both own.
sam = {"red", "blue", "green"}
alex = {"blue", "yellow", "green"}
# Intersection: SHARED marbles only
shared = sam & alex
# OR use .intersection()
shared = sam.intersection(alex)
print(shared)
# {'blue', 'green'}
๐จ Visual
graph TD A["Sam: ๐ด ๐ต ๐ข"] --> C["Find Twins"] B["Alex: ๐ต ๐ก ๐ข"] --> C C --> D["๐ต ๐ข"] D --> E["Only these are in BOTH!"]
Remember: & or .intersection() = Only the matching ones!
3๏ธโฃ Set Difference: โWhatโs ONLY in MY Box?โ
The Big Idea: Difference shows whatโs special to one box โ not in the other.
Sam wants to know: โWhich marbles do I have that Alex doesnโt?โ
sam = {"red", "blue", "green"}
alex = {"blue", "yellow", "green"}
# Sam's unique marbles (not in Alex's box)
only_sam = sam - alex
# OR use .difference()
only_sam = sam.difference(alex)
print(only_sam)
# {'red'}
# Alex's unique marbles
only_alex = alex - sam
print(only_alex)
# {'yellow'}
๐จ Visual
graph TD A["Sam: ๐ด ๐ต ๐ข"] B["Alex: ๐ต ๐ก ๐ข"] A --> C["Sam - Alex"] C --> D["๐ด Only Sam!"] B --> E["Alex - Sam"] E --> F["๐ก Only Alex!"]
Remember: - or .difference() = Mine but not yours!
4๏ธโฃ Symmetric Difference: โWhatโs NOT Shared?โ
The Big Idea: Find everything thatโs in ONE box but NOT in BOTH.
Itโs like saying: โShow me all the special, non-matching marbles!โ
sam = {"red", "blue", "green"}
alex = {"blue", "yellow", "green"}
# Marbles in ONE box only (not shared)
unique_to_either = sam ^ alex
# OR use .symmetric_difference()
unique_to_either = sam.symmetric_difference(alex)
print(unique_to_either)
# {'red', 'yellow'}
๐จ Visual
graph TD A["Sam: ๐ด ๐ต ๐ข"] B["Alex: ๐ต ๐ก ๐ข"] A --> C["Symmetric Diff"] B --> C C --> D["๐ด ๐ก"] D --> E["Unique to ONE box only"]
Remember: ^ or .symmetric_difference() = The oddballs!
5๏ธโฃ Set Comparison Methods: โWho Has More?โ
Sets can be compared like people comparing their collections!
๐น Subset: โDoes Alex have everything Sam has?โ
small = {"blue", "green"}
big = {"red", "blue", "green", "yellow"}
# Is small inside big?
print(small.issubset(big)) # True
print(small <= big) # True
# Is small a PROPER subset? (smaller, not equal)
print(small < big) # True
๐น Superset: โDoes Sam contain Alexโs entire collection?โ
big = {"red", "blue", "green", "yellow"}
small = {"blue", "green"}
# Does big contain all of small?
print(big.issuperset(small)) # True
print(big >= small) # True
# Proper superset (strictly bigger)
print(big > small) # True
๐น Disjoint: โZero Matches!โ
cats = {"whiskers", "mittens"}
dogs = {"buddy", "max"}
# Do they share anything?
print(cats.isdisjoint(dogs)) # True (nothing shared!)
foods = {"pizza", "tacos"}
favorites = {"pizza", "ice cream"}
print(foods.isdisjoint(favorites)) # False (pizza!)
๐ Quick Comparison Chart
| Method | Symbol | Meaning |
|---|---|---|
issubset() |
<= |
All my items are in yours |
issuperset() |
>= |
I have all of your items |
< |
โ | Proper subset (smaller) |
> |
โ | Proper superset (bigger) |
isdisjoint() |
โ | Zero overlap |
6๏ธโฃ Set Comprehensions: โBuild Sets Like a Pro!โ
The Big Idea: Create sets with a magic one-liner!
Just like a factory that picks and transforms items automatically.
๐น Basic Set Comprehension
# Squares of numbers 1 to 5
squares = {x**2 for x in range(1, 6)}
print(squares)
# {1, 4, 9, 16, 25}
๐น With a Condition (Filter)
# Only even squares
even_squares = {x**2 for x in range(1, 11) if x % 2 == 0}
print(even_squares)
# {4, 16, 36, 64, 100}
๐น Transform Strings
words = ["Hello", "WORLD", "Python"]
# Get unique first letters (lowercase)
first_letters = {word[0].lower() for word in words}
print(first_letters)
# {'h', 'w', 'p'}
๐น From Another Collection
numbers = [1, 2, 2, 3, 3, 3, 4]
# Unique doubled values
doubled = {n * 2 for n in numbers}
print(doubled)
# {2, 4, 6, 8}
๐จ Comprehension Formula
graph LR A["{expression}"] --> B["for item in collection"] B --> C["if condition"] C --> D["= NEW SET!"]
Pattern: {expression for item in collection if condition}
๐ Summary: Your 6 Magic Tricks!
| Operation | Symbol | Method | What It Does |
|---|---|---|---|
| Union | | |
.union() |
All items combined |
| Intersection | & |
.intersection() |
Only shared items |
| Difference | - |
.difference() |
Mine, not yours |
| Symmetric Diff | ^ |
.symmetric_difference() |
Unique to one |
| Subset | <= |
.issubset() |
Am I inside you? |
| Superset | >= |
.issuperset() |
Do I contain you? |
Set Comprehension Template
{expression for item in collection if condition}
๐ You Did It!
You now know how to:
- Combine sets with Union
- Find twins with Intersection
- Spot differences with Difference
- Find oddballs with Symmetric Difference
- Compare sizes with Comparison Methods
- Build sets fast with Comprehensions
These tricks work with any collection โ names, numbers, even pizza toppings! ๐
Go experiment. Mix. Match. Create!
