The intersection (A∩B) of two sets A and B is the set that contains all the elements common between both the sets.
We can perform an intersection between multiple sets too. Following image shows the set intersection example between two sets and three sets.
Set Intersection
Python set intersection
In Python, we can use set
class intersection()
function to get the intersection of two sets.
Let’s look at an example of the intersection between two sets.
1 2 3 4 5 6 7 8 |
set1 = set('abcde') set2 = set('ae') print(set1) print(set2) # two sets intersection print(set1.intersection(set2)) |
Output:
1 2 3 4 5 6 |
{'a', 'e', 'b', 'd', 'c'} {'a', 'e'} {'a', 'e'} <img class="alignnone wp-image-22528 size-full" src="http://all-learning.com/wp-content/uploads/2019/01/Python-Two-Sets-Intersection.png" alt="Python Two Sets Intersection" width="1200" height="628" /> |
Python Two Sets Intersection
The intersection() function takes multiple set arguments too. Let’s look at another example of the intersection between multiple sets.
1 2 3 4 5 6 |
set1 = set('abcde') set2 = set('ae') set3 = {'a'} print(set1.intersection(set2, set3)) |
Output: {'a'}
Python Multiple Set Intersection
Set intersection without arguments
We can call intersection() function without an argument too. In this case, a copy of the set will be returned.
Let’s see if the returned copy refers to the same set or a different one.
1 2 3 4 5 6 7 8 9 10 |
set1 = set('ab') set4 = set1.intersection() print(set4) # check if shallow copy or deep copy set1.add('0') set1.remove('a') print(set1) print(set4) |
Output:
1 2 3 4 5 |
{'b', 'a'} {'0', 'b'} {'c', 'b', 'a'} |
Reference: Official Documentation