{"id":25051,"date":"2021-11-10T09:37:29","date_gmt":"2021-11-10T04:07:29","guid":{"rendered":"https:\/\/python-programs.com\/?p=25051"},"modified":"2021-11-10T09:37:29","modified_gmt":"2021-11-10T04:07:29","slug":"python-set-intersection-method-with-examples","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-set-intersection-method-with-examples\/","title":{"rendered":"Python Set intersection() Method with Examples"},"content":{"rendered":"
Prerequisite:<\/h5>\n

Python set() Function with Examples<\/span><\/a><\/p>\n

Set intersection() Method in Python:<\/strong><\/p>\n

The intersection() method returns a set containing the similarity(common items) of two or more sets.<\/p>\n

If the comparison is done with more than two sets, the returned set contains only items that exist in both sets, or in all sets if the comparison is done with more than two sets.<\/p>\n

For Example:<\/strong><\/p>\n

If P and Q are two distinct sets. A set intersection between P and Q is :<\/p>\n

Let P={4,5,6,7}<\/p>\n

Q={5,6,8,9}<\/p>\n

P intersection Q = {5,6}<\/p>\n

Since {5,6} are only the common elements in both the sets<\/p>\n

Syntax:<\/strong><\/p>\n

set.intersection(set1, set2,..........)<\/pre>\n

Parameters<\/strong><\/p>\n

set1:<\/strong> This is Required. The set to look for similar items in<\/p>\n

set2: <\/strong>This is Optional. The other set to look for similar items in. You are free to compare as many sets as you want. Use a comma to separate the sets.<\/p>\n

Return Value:<\/strong><\/p>\n

The intersection() method returns the intersection of set A and all the other sets (passed as argument).<\/p>\n

If the argument is not passed to an intersection(), a shallow copy of the set is returned (A).<\/p>\n

Examples:<\/strong><\/p>\n

Example1:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given first set =  {10, 20, 30, 40, 50}\r\nGiven second set = {100, 20, 80, 70, 30}\r\nGiven third set = {200, 40, 80, 30}<\/pre>\n

Output:<\/strong><\/p>\n

firstset intersection secondset =  {20, 30}\r\nfirstset intersection thirdset =  {40, 30}\r\nsecondset intersection thirdset =  {80, 30}<\/pre>\n

Example2:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given first set =  {'a', 'b', 'c'}\r\nGiven second set = {'p', 'q', 'r'}\r\nGiven third set = {'q', 'a', 'k'}\r\n<\/pre>\n

Output:<\/strong><\/p>\n

firstset intersection secondset =  set()\r\nfirstset intersection thirdset =  {'a'}\r\nsecondset intersection thirdset =  {'q'}<\/pre>\n

Set intersection<\/strong>() Method with Examples in Python<\/h2>\n