Python set intersection

Filed Under: Python

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

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.


set1 = set('abcde')

set2 = set('ae')

print(set1)
print(set2)

# two sets intersection
print(set1.intersection(set2))

Output:


{'a', 'e', 'b', 'd', 'c'}
{'a', 'e'}
{'a', 'e'}
Python Two Sets Intersection

Python Two Sets Intersection

The intersection() function takes multiple set arguments too. Let’s look at another example of the intersection between multiple sets.


set1 = set('abcde')
set2 = set('ae')
set3 = {'a'}
print(set1.intersection(set2, set3))

Output: {'a'}

Python Multiple Set Intersection

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.


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:


{'b', 'a'}
{'0', 'b'}
{'c', 'b', 'a'}
You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

Comments

  1. ACHOUR says:

    please rectify the part of Python set intersection section :

    S2 Π S3 = {C,F}

    you have written S2 Π S2 = {C,F}

    thank’s

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages