Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to find the union and intersection of two sets in Python

Muhammad Muzammil

Overview

A Python set is a collection of elements of any data type except mutable elements (such as lists, sets, dictionaries, etc.). However, no element can be repeated. The figure below shows examples of two sets, AA and BB.

Python’s built-in data type set() and its helper functions can be leveraged to make sets and perform different operations on them. Union and intersection are the two of the most commonly performed operations on sets and can be found with the union() and intersection() functions.

For intersection of AA and BB, you can use the following syntax:

intersection_set = A.intersection(B)

For union:

union_set = A.union(B)

Intersection

The intersection of two sets is the collection of elements that are present in both sets. In the example of sets AA and BB, we can see that the element 22 is common in both. Hence, the intersection of AA and BB will be {2}\{ 2 \}.

Code

The program below prints the intersection of AA and BB.

def main ():
	set_A = set({1, 2, "hello"})
	set_B = set({2, 3, 10})

	set_intersection = set_A.intersection(set_B)
	print(set_intersection)
main ()

Union

The union of two sets is the set of all elements that are present in the two sets. In AA and BB, the collection of all elements is {1,2,hello,3,10}\{1, 2, 'hello', 3, 10\}.

Code

The Python program below shows how to find the union of two sets.

def main ():
	set_A = set({1, 2, "hello"})
	set_B = set({2, 3, 10})

	set_intersection = set_A.union(set_B)
	print(set_intersection)
main ()

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring