Related Tags

python
communitycreator

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

### 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, $A$ and $B$.

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 $A$ and $B$, 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 $A$ and $B$, we can see that the element $2$ is common in both. Hence, the intersection of $A$ and $B$ will be $\{ 2 \}$.

### Code

The program below prints the intersection of $A$ and $B$.

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 $A$ and $B$, the collection of all elements is $\{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

CONTRIBUTOR

RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time