Python Set intersection() Method
In this tutorial, we will understand about the python set intersection() method and its uses.
Python Set intersection() Method
The Python set intersection() method returns a new set containing elements that are common to both sets. It can also be written using the ampersand operator (&). The original sets remain unchanged.
The syntax of the intersection() method is:
1
2
3
set.intersection(set2)
# or
set1 & set2
Python set intersection() Parameters
The intersection() method takes one parameter:
- set2: Another set, or any iterable whose common elements will be found.
Here are examples demonstrating the intersection() method:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Example 1: Basic intersection
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
result = set1.intersection(set2)
print(result) # Output: {4, 5}
# Example 2: Using operator syntax
numbers1 = {1, 2, 3, 4}
numbers2 = {3, 4, 5, 6}
result = numbers1 & numbers2
print(result) # Output: {3, 4}
# Example 3: Multiple set intersection
set1 = {1, 2, 3, 4}
set2 = {2, 3, 4, 5}
set3 = {3, 4, 5, 6}
result = set1.intersection(set2, set3)
print(result) # Output: {3, 4}
The intersection() method is useful when you need to find common elements between sets.
This post is licensed under CC BY 4.0 by the author.