Python

Python Set intersection Method

Hello in this tutorial, we will explain how to set the intersection method in python programming.

1. Introduction

The intersection() method in python programming returns a set containing common elements from one or more given sets. Its syntax representation is given as below:

set.intersection(set1, set2 ... etc)
Python Set intersection

The parameter set1 is required to search for equal items and set2 . . . are the optional sets.

1.1 Setting up Python

If someone needs to go through the Python installation on Windows, please watch this link. You can download the Python from this link.

2. Python Set intersection Method

I am using JetBrains PyCharm as my preferred IDE. You are free to choose the IDE of your choice.

2.1 Python Set intersection Method

Let us understand this with the help of a code snippet.

Python Set intersection Method

# Python Set intersection Method
# intersection(...) method returns a set containing common elements from one or more given sets
# set1
set1 = {
    'apple',
    'google',
    'amazon'
}
# set2
set2 = {
    'google',
    'microsoft',
    'amazon'
}

# set3
set3 = {
    'google'
}
intersection_set1 = set1.intersection(set2)
print(intersection_set1)
print('\n')
intersection_set2 = set1.intersection(set2, set3)
print(intersection_set2)

If everything goes well the following output will be shown in the IDE console.

Console Output

{'amazon', 'google'}
{'google'}

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

3. Summary

In this tutorial, we showed:

  • intersection() method in python
  • A sample program to set intersection method in python

You can download the source code of this tutorial from the Downloads section.

4. Download the Project

This was a tutorial of intersection() method in python.

Download
You can download the full source code of this example here: Python Set intersection Method

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button