Python Set intersection() Method
The set.intersection()
method returns a new set with the elements that are common in the given sets.
Syntax:
set.intersection(*other_sets)
Parameters:
other_sets: Optional. A comma separates one or more sets. Returns the shallow copy of a set if no parameter is passed.
Return Value:
A set with common elements among all sets.
The following example demonstrates the set.intersection()
method.
nums = {1, 2, 3, 4, 5 }
oddNums = {1, 3, 5, 7, 9}
commonNums = nums.intersection(oddNums)
print("Common elements in nums and oddNums are: ", commonNums)
numscopy = nums.intersection() # returns shallow copy if no argument passed
print("Shallow copy: ", numscopy)
Common elements in nums and oddNums are: {1, 3, 5}
Shallow copy: {1, 2, 3, 4, 5 }
The set.intersection()
method can work on multiple sets too.
nums = {1, 2, 3, 4, 5}
oddNums = {1, 3, 5, 6, 7, 9}
primeNums = {2, 3, 5, 7}
commonNums = nums.intersection(oddNums, primeNums)
print("Common elements: ", commonNums)
Common elements: {3, 5}
The &
operator can also be used to find the intersection of sets.
nums = {1,2,3,4,5,6,7,8,9,10}
oddNums = {1,3,5,6,7,9}
primeNums = {2,3,5,7}
commonNums = Nums & oddNums & primeNums
print("Common elements: ", commonNums)
Common elements: {3, 5}
It returns an empty set if no common elements are found.
nums = {10, 20, 30, 40}
oddNums = {1, 3, 5, 6, 7, 9}
commonNums = nums & oddNums
print("Common elements: ", commonNums)
commonNums = nums.intersection(oddNums)
print("Common elements: ", commonNums)
Common elements: set()