What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Python Set Intersection with Examples (& code)

  • Jul 18, 2023
  • 6 Minute Read
Python Set Intersection with Examples (& code)

Like mathematics, Python also enables the features of set intersection and generates a completely new set as the output. In this article, let us study how to find set intersections in Python along with examples and output.

What is a Set Intersection?

Python sets are one of the most fundamental data structures which enable you to store the elements in sequential form. The data elements in sets are represented inside the curly brackets, and commas separate each element. Sets are unordered, unchangeable, and unindexed, which means you can remove the set element and add new elements but cannot change the elements already present in the set. 

The intersection of two sets can be defined as the formation of a new set containing the common elements of both the given sets. Set intersection is not a constraint between two sets, and therefore, you can have as many sets as you want to find the common elements between them. Suppose the intersection of set A and set B is a set containing all the elements present in set A and set B.

The below image shows the Venn diagram of set intersections, i.e., representing the common elements from both sets.

Example of set intersection

Now you know what we mean by set interaction, let's learn how to find it.

How to Find the Intersection of Sets in Python?

We will learn about different ways to get the intersection of two sets in Python programming:

1) Using intersection() function

Python's intersection() function is an in-built method by which you can perform the set intersection that enables you to identify the elements that are shared by two or more sets. The intersection() function does not alter the initial sets, but a new set comprising the shared components of the intersecting sets is returned.

The syntax of the intersection function is given below:

set A.intersection(set B, set C, set D, )

 

Here, the intersection method takes a parameter as the set variable for which the common element is found. It returns as the new set containing the common elements of all the sets(set B, set C, set D…). Check out the below example to understand the working of the intersection() method. For example:

X = {1, 3, 5, 7}
Y = {2, 3, 5, 8}

print(X.intersection(Y))

 

Output:

{3, 5}

 

The intersection() function in Python has a temporal complexity of O(min(len(set1), len(set2))), where set1 & set2 are the sets that are being intersected. This indicates that the time needed to complete the intersection operation grows linearly as the smaller set's size does. 

2) Using intersection operator(&)

Apart from the Python inbuilt function, you can also perform set intersection using the intersection operator. The ampersand symbol (&) is used to symbolize the Python Set Intersection symbol, and is employed to perform an intersection operation between two or more sets.

Here, the operator is placed between both sets and as a result, the completely new set is formed as the output containing the common elements of sets. For example:

X = {1, 3, 5, 7, 8}
Y = {2, 3, 5, 8}
Z = {0, 2, 4, 8}

print(X & Y)
print(Y & Z)
print(X & Y & Z)

 

Output:

{8, 3, 5}
{8, 2}
{8}

 

3) Using empty set for set intersection

Set intersection returns the common elements of any two sets, but what if the sets are empty and do not contain any elements in them? The output after performing the intersection will also be an empty set as there are no common elements in the given sets. For example:

X = {}
Y = {}
print(set(X).intersection(set(Y)))

 

Output:

set()

 

4) Python Intersection of Multiple Sets

The & operator or the intersection() method in Python can be used to execute an intersection of multiple sets. The intersection() method is employed to perform an intersection of many sets, whereas the & operator is employed to perform an intersection of two sets.

Utilizing the intersection() method, we may execute an intersection of multiple sets by passing the sets as arguments, as demonstrated in the example below:

# Create three sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set3 = {5, 6, 7, 8, 9}

# Perform intersection of multiple sets
intersection = set1.intersection(set2, set3)

# Print the intersection
print(intersection)

 

Output:

{1,2,3,4,5,6,7,8,9,10,11,12,13}

 

In the aforementioned example, we produced sets 1, 2, and 3. The intersection of all three sets was then calculated using the intersection() method, and the outcome was saved in the intersection variable. The common elements that exist in all the sets getting intersected are contained in the new set that is returned by the intersection() method.

The intersection set's contents, which include the elements shared by all three sets, were then printed.

If we have a lot of sets, we can also send them as a variable-length input list using the intersection() method and the * operator. For instance:

# Create five sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set3 = {5, 6, 7, 8, 9}
set4 = {8, 9, 10, 11, 12}
set5 = {9, 10, 11, 12, 13}

# Perform intersection of multiple sets
intersection = set1.intersection(set2, set3, set4, set5)

# Print the intersection
print(intersection)

 

Output:

{1,2,3,4,5,6,7,8,9,10,11,12,13}

 

In this instance, we made five sets: Sets 1, 2, 3, 4, and 5. After that, we performed an intersection operation among each of the five sets using the intersection() function and the * operator, and we saved the outcome in the intersection variable. The common elements present in each of the sets being intersected are contained in the new set that is returned by the intersection() method.

The intersection set's contents, which include the elements shared by all five sets, were then printed.

set intersection() method vs set intersection operator (&)

To find the set intersection, the intersection() method accepts any iterable such as lists, strings, and dictionaries, etc. However, the set intersection operator only allows a set data structure to find the intersection.

As the intersection method accepts any iterable, note that it will convert every iterable to a set before intersecting them and generating the output accordingly. For example:

X = {1, 3, 5}
Y = [1, 5, 9]

result = X.intersection(Y)

print(result)

 

Output:

{1, 5}

 

In the above example, the intersection is performed between a set and a list; however, the intersection method converted the list to a set internally and generates the output. At the same time, the intersection operator will not accept any iterable and hence raise the error if you use them. Look at the code below:

X = {1, 2, 3}
Y = [2, 3, 4]

result = X & Y
print(result)

 

Output:

TypeError: unsupported operand type(s) for &: 'set' and 'list'

 

Also, learn how to find set differences in Python to understand and complete both these concepts at once.

Summary

Python sets are the most fundamental data structure used to store sequential data into a single variable. It is recommended to learn all these methods and efficiently perform the explicit set intersection during programming in Python. Get the best Python assignment help online for more explanation.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Shivali Bhadaniya
I'm Shivali Bhadaniya, a computer engineer student and technical content writer, very enthusiastic to learn and explore new technologies and looking towards great opportunities. It is amazing for me to share my knowledge through my content to help curious minds.