Menu Close

Python Set intersection() Method

Python set intersection

In this set method tutorial, we are going to learn the set intersection function using different examples. Python set intersection() method is used to return a new set that contains items common in all sets.

In the previous tutorial, we have seen all about python set along with some examples. Click here to learn all about sets in Python, so that you can easily understand this tutorial.

Python set intersection() method

set intersection method is a set function that returns a set that contains items that only exist in both sets.

Syntax

Set intersection function syntax is:-

set.intersection(set1, set2, set3, ..... etc)

Parameter

intersection function in python accepts multiple parameters but one parameter is mandatory.

  • set1 – Required. A set to search for equal items.
  • set2 – Optional. A set to search for equal items.

Return Value

The return value of set intersection method is new set that contains item exist in both sets.

set intersection method example

Example 1:

intersection() function with only one parameter.

my_set1 = { 'Python', 'Java', 'JavaScript', 'C++'}
my_set2 = { 'HTML', 'CSS', 'Python', 'C++'}
result = my_set1.intersection(my_set2)
print(result)

Output will be:- {‘C++’, ‘Python’}

Example 2:

set intersection method with multiple parameters.

my_set1 = {'Python', 'Java', 'JavaScript', 'C++'}
my_set2 = {'HTML', 'CSS', 'Python', 'C++'}
my_set3 = {'Ruby','C++','Python', 'Lua'}
result = my_set1.intersection(my_set2, my_set3)
print(result)

Output will be:- {‘C++’, ‘Python’}

Conclusion

Here we have learned all about the python set intersection() method. Python set intersection() method returns a new set that contains only items that exist in both sets. intersection function in Python accepts more than one parameters

I how this is very useful for you. To learn Python from scratch to advance, this place will best for you.

Other methods


For More Information:- Click Here

Python Set discard() Method
Python Set intersection_update() Method

Related Posts