How to Intersect Sets in Python: Best Example

Here’s an example to use Intersect in Python, and differences between Intersect and Difference methods.

Python intersection method

Here are two sets (s_1 and s_2). Intersection method applied on these sets to extract common values of both the sets.


  1. Python logic to intersect sets
  2. Python: Intersection Vs. Difference

Python logic to intersect sets

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

Python: Intersection Vs. Difference

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.