Set Operations

Back

Loading concept...

๐ŸŽญ 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["&#123;expression&#125;"] --> 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!

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.