Set Intersection in Python Exclusive Example

Two or more sets you can intersect and get common values in python. Here is a intersection method available for this purpose.

Python intersection method

In the example below you will find two sets (s_1 and s_2). I used intersect method. You can find values common to both sets in the result.

Set intersection example

Below exclusive example uses two sets. The s_1 and s_2 are two lists. The s_3 is the resultant set that will create after the intersection operation.

s_1 = {"kiwi", "banana", "peanut butter"}
s_2 = {'kiwi', 'spinach', 'banana'}
s_3=  s_1.intersection(s_2)

Result of intersection

You can see sets s_1 and s_2 in the display. Then, s_3 set, which is the intersection of s_1 and s_2. Here’s the output.

{'kiwi', 'peanut butter', 'banana'} #s_1
{'kiwi', 'spinach', 'banana'}   #s_2
{'kiwi', 'banana'}  #s_3

** Process exited - Return Code: 0 **
Press Enter to exit terminal

The difference Vs. intersection methods

The difference() method opposite to the intersection() method. Which enables our ERP banking application to find the same values in different lists. It is helpful to find matching values (key) and to create joins and unions in data science.



Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.