Python Set Operations

In the last lesson, we learned about Python Introduction to Sets. Now let’s combine and compare sets with common set operations.

Let’s Talk About Combining Sets

We know what a set is. It is an unordered collection of unique items.

Now imagine we have two sets. And we want to combine them in different ways. Maybe we want all the items from both. Maybe we only want the items they have in common. Maybe we want the items that are in one but not the other.

That is what set operations are for.

Think of it like Venn diagrams from school. Two circles that overlap. And we can look at different parts of the diagram. The whole thing. The overlapping part. The parts that are only in one circle.

Python gives us all these operations. And they are very easy to use.

Union β€” All Items from Both Sets

The union of two sets is a new set with all the items from both. Duplicates are removed automatically.

We can use the | operator or the union() method.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
print(union_set)

Output

{1, 2, 3, 4, 5}

Or using the method:

union_set = set1.union(set2)
print(union_set)

Same result.

Notice that 3 appears in both sets. But in the union, it appears only once. Because sets only keep unique items.

Intersection β€” Only the Common Items

The intersection of two sets is a new set with only the items that are in both sets.

We can use the & operator or the intersection() method.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1 & set2
print(intersection_set)

Output

{3}

Or using the method:

intersection_set = set1.intersection(set2)
print(intersection_set)

Same result.

Only 3 is in both sets. So the intersection is 3.

Difference β€” Items in One Set but Not the Other

The difference of two sets is a new set with items that are in the first set but not in the second.

We can use the - operator or the difference() method.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1 - set2
print(difference_set)

Output

{1, 2}

Or using the method:

difference_set = set1.difference(set2)
print(difference_set)

Same result.

It gives items that are in set1 but not in set2. Notice that 3 is in both, so it is not included. And 4, 5 are only in set2, so they are not included either.

If we reverse the order:

print(set2 - set1)

Output

{4, 5}

Because now we want items in set2 but not in set1.

Symmetric Difference β€” Items in Either Set but Not Both

The symmetric difference of two sets is a new set with items that are in one set or the other, but not in both.

We can use the ^ operator or the symmetric_difference() method.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
sym_diff = set1 ^ set2
print(sym_diff)

Output

{1, 2, 4, 5}

Or using the method:

sym_diff = set1.symmetric_difference(set2)
print(sym_diff)

Same result.

It includes everything except the common items. So 3 is excluded because it is in both. Everything else is included.

Subset and Superset in Python

A set is a subset of another if all its items are in the other set.

We can use the <= operator or the issubset() method.

set1 = {1, 2}
set2 = {1, 2, 3, 4}
print(set1 <= set2)

Output

True

Because every item in set1 is also in set2.

We can check if a set is a superset of another using >= or issuperset().

print(set2 >= set1)

Output

True

Because set2 contains all items of set1.

Disjoint Sets in Python

Two sets are disjoint if they have no items in common.

We can use the isdisjoint() method.

set1 = {1, 2, 3}
set2 = {4, 5, 6}
print(set1.isdisjoint(set2))

Output

True

If they share at least one item, it returns False.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.isdisjoint(set2))

Output

False

Updating Sets in Place

All the operations above create new sets. But we can also update a set in place using methods that end with _update.

For example, update() adds all items from another set to the current set.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.update(set2)
print(set1)

Output

{1, 2, 3, 4, 5}

Similarly, intersection_update() keeps only the items that are in both sets.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.intersection_update(set2)
print(set1)

Output

{3}

difference_update() removes items that are in another set.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.difference_update(set2)
print(set1)

Output

{1, 2}

symmetric_difference_update() keeps only the items that are in one set or the other, but not both.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.symmetric_difference_update(set2)
print(set1)

Output

{1, 2, 4, 5}

These update methods modify the original set. They do not create a new one.

Python Set Operations: A Real-Life Example

Let’s say we have two groups of friends. One group likes pizza. The other likes burgers.

pizza_lovers = {"Alex", "Sam", "John", "Emma"}
burger_lovers = {"Sam", "John", "David", "Emma"}
print("All friends:", pizza_lovers | burger_lovers)
print("Like both:", pizza_lovers & burger_lovers)
print("Only pizza:", pizza_lovers - burger_lovers)
print("Only burgers:", burger_lovers - pizza_lovers)
print("Like exactly one:", pizza_lovers ^ burger_lovers)

Output

All friends: {'Alex', 'Sam', 'John', 'David', 'Emma'}
Like both: {'Sam', 'John', 'Emma'}
Only pizza: {'Alex'}
Only burgers: {'David'}
Like exactly one: {'Alex', 'David'}

That is a very clear way to analyze overlapping groups.

Another Example β€” Finding Unique Words

sentence1 = "the quick brown fox"
sentence2 = "the lazy dog"
words1 = set(sentence1.split())
words2 = set(sentence2.split())
print("All unique words:", words1 | words2)
print("Common words:", words1 & words2)
print("Words only in first:", words1 - words2)

Output

All unique words: {'the', 'quick', 'brown', 'fox', 'lazy', 'dog'}
Common words: {'the'}
Words only in first: {'quick', 'brown', 'fox'}

That is useful for text analysis.

Common Mistakes with Python Set Operations

Mistake 1: Using the Wrong Operator

set1 = {1, 2}
set2 = {2, 3}
print(set1 + set2) # Error!

Sets do not support +. We use | for union.

Mistake 2: Thinking These Operations Modify the Original Sets

set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = set1 | set2
print(set1) # {1, 2, 3}
print(set2) # {3, 4, 5}

The operators and methods like union(), intersection(), etc. return new sets. The original sets are unchanged.

If we want to modify in place, we use the _update methods.

Mistake 3: Using & with Lists

list1 = [1, 2, 3]
list2 = [3, 4, 5]
print(list1 & list2) # Error!

The set operators only work on sets. We convert to sets first.

print(set(list1) & set(list2))

Mistake 4: Forgetting That Sets Are Unordered

set1 = {1, 2, 3}
set2 = {3, 2, 1}
print(set1 == set2)

Output

True

Because sets are unordered, the order does not matter. They are equal if they have the same items.

Next, we will learn about Python Set Union and combine all unique items from multiple sets.