0
0
Pythonprogramming~5 mins

Union and intersection in Python

Choose your learning style9 modes available
Introduction

Union and intersection help you find common or combined items from two groups. They make comparing lists or sets easy.

You want to combine two friend lists without repeats.
You want to find common interests between two people.
You want to merge two sets of data without duplicates.
You want to find items that appear in both shopping lists.
You want to check shared skills between two teams.
Syntax
Python
set1.union(set2)
set1.intersection(set2)

union() returns all unique items from both sets.

intersection() returns only items found in both sets.

Examples
This shows all unique numbers from both sets: 1, 2, 3, 4, 5.
Python
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b))
This shows only the number 3, which is in both sets.
Python
a = {1, 2, 3}
b = {3, 4, 5}
print(a.intersection(b))
Sample Program

This program finds all unique friends from two groups and also finds friends they both have.

Python
friends_a = {"Alice", "Bob", "Charlie"}
friends_b = {"Bob", "Diana", "Eve"}

all_friends = friends_a.union(friends_b)
common_friends = friends_a.intersection(friends_b)

print("All friends:", all_friends)
print("Common friends:", common_friends)
OutputSuccess
Important Notes

Sets automatically remove duplicates, so union never repeats items.

Order of items in sets when printed may vary because sets are unordered.

Summary

Union combines all unique items from two sets.

Intersection finds only items common to both sets.

Use these to compare or merge groups easily.