Skip to main content
Crowdfunding
Python + AI for Geeks
Practice

Intersection, Union, Difference Operations

Set is highly useful when performing set operations such as intersection, union, and difference, which you might have learned in math class.

These set operations are widely used in data analysis, algorithm design, logic implementation, and various other fields.


Intersection

An intersection is a set that contains elements common to both sets.

You can find the intersection using the intersection() method or the & operator.

Set Intersection Operation
set_a = {1, 2, 3}
set_b = {3, 4, 5}

intersection = set_a & set_b
# or set_a.intersection(set_b)

print("intersection:", intersection)
# Output: {3}

Union

A union is a set that contains all elements from both sets.

Use the union() method or the | operator.

Set Union Operation
set_a = {1, 2, 3}
set_b = {3, 4, 5}

union = set_a | set_b
# or set_a.union(set_b)

print("union:", union)
# Output: {1, 2, 3, 4, 5}

Difference

A difference is a set containing elements that are in the first set but not in the second set.

You can find the difference using the difference() method or the - operator.

Set Difference Operation
set_a = {1, 2, 3}
set_b = {3, 4, 5}

difference = set_a - set_b
# or set_a.difference(set_b)

print("difference:", difference)
# Output: {1, 2}

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.