INSTACK 360

Sets & Mathematical Set Operations

Discover Sets to eliminate duplicates instantly and perform blazing-fast mathematical operations like union and intersection.

Intermediate 5 min read

The Power of Uniqueness

A Set in Python is an unordered collection of entirely unique elements. Sets do not record element positions (indexes), meaning you cannot do `myset[0]`.

Instantly Removing Duplicates

The most common use case for a set in the real world is taking a messy list full of duplicates and cleaning it instantly by casting it to a set.

emails = ["a@a.com", "b@b.com", "a@a.com", "c@c.com"]
unique_emails = list(set(emails))
# Result: ["a@a.com", "b@b.com", "c@c.com"]

Mathematical Superpowers

Sets excel at relational mathematics. Let's say you have two sets of friends on different social networks, and you want to analyze them:

fb_friends = {"Alice", "Bob", "Charlie"}
ig_friends = {"Charlie", "David", "Alice"}

# Union (|): Everyone from both lists combined
all_friends = fb_friends | ig_friends

# Intersection (&): Friends who are on BOTH platforms
mutual_friends = fb_friends & ig_friends

# Difference (-): Friends on FB but NOT on IG
fb_only = fb_friends - ig_friends