Python Set Intersection

python-set-intersection-ipcisco-1

We can compare different sets and find the common items in these sets with Python Set Intersection method. This can be done with this set method or we can use “&” operator to do this. To understand how to use Python Set Intersection, let’s show some examples.

 

Below, we will compare two python set and find the common items in it. The return of this code will be also a set that includes these common items.

 

numbers1 = {10,15,25,30,45,55}
numbers2 = {10,20,30,40}
print(numbers1.intersection(numbers2))
{10, 30}

 

 


You can also learn Python Set Operations


 

python-set-intersection-ipcisco-1

 

The below code with “&” operator will also do the same thing with Python Set Intersection method.

 

numbers1 = {10,15,25,30,45,55}
numbers2 = {10,20,30,40}
print(numbers1 & numbers2)

 

{10, 30}

 


You can also checck Python Set Union Method


 

 

You can also watch the video of this lesson!

 

Now, let’s compare more than two sets with the help of Python Set Intersection. Below, we will compare three sets and find the common items used in these python sets.

 

numbers1 = {10,15,25,30,45,55}
numbers2 = {10,20,30,40}
numbers3= {10,100,1000}
print(numbers1.intersection(numbers2, numbers3))

 

The output of this python code will be 10 in a set, because in all sets above, 10 is common.

 

{10}

 

The same code with “&” operator will give the same output:

 

numbers1 = {10,15,25,30,45,55}
numbers2 = {10,20,30,40}
numbers3= {10,100,1000}
print(numbers1 & numbers2 & numbers3)
{10}

 

python-set-intersection-ipcisco-2

 

Let’s give more examples for intersection with string sets. Below, we will compare two python sets. These are two string sets.

 

dwarves1 = {"Thorin", "Balin", "Dwalin"}
dwarves2 = {"Gimli", "Balin", "Thorin"}
print(dwarves1.intersection(dwarves2))

 

{'Balin', 'Thorin'}

 

We can use “&” operator to get the same result like below:

 

dwarves1 = {"Thorin", "Balin", "Dwalin"}
dwarves2 = {"Gimli", "Balin", "Thorin"}
print(dwarves1 & dwarves2)

 

{'Balin', 'Thorin'}

 

In this lesson, we have talked about Python Set Intersection method. We have compared different sets and find the common items in these sets with both this method or “&” operator. These methods are used especially to find the common members of different items. You can increase your coding examples for this lesson by yourself in this Python Programming Course.

Back to: Python Programming Course > Python Sets

Leave a Reply

Your email address will not be published.

IPCisco is the Winner of 2019 “Best Certification Study Journey” Category! We are also Finalist of 2020 & 2021 in Cisco IT Blog Awards!

Cisco-ITBlogAwards-2019-Winner-IPCisco-k
ITBlogAwards_2020_Badge-Finalist-BestCertStudy-ipcisco
ITBlogAwars-2021-ipcisco

Python Programming Course

Collapse
Expand
IPCisco on Social Media!