Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Intersection() function Python
In this article, we will learn about the intersection() function that can be performed on any given set. According to mathematics, intersection means finding common elements from two or more sets.
Syntax
<set_name>.intersection(<set1>, <set2>, ...)
Parameters
The intersection() method accepts one or more iterables (sets, lists, tuples) as arguments and returns their common elements.
Return Value
Returns a new set containing common elements present in all the sets passed as arguments.
Example 1: Basic Intersection
letters_1 = {'t', 'u', 'o', 'r', 'i', 'a', 'l'}
letters_2 = {'p', 'o', 'i', 'n', 't'}
# Intersection of two sets
result = letters_1.intersection(letters_2)
print("letters_1 intersection letters_2:", result)
letters_1 intersection letters_2: {'i', 'o', 't'}
Example 2: Multiple Set Intersection
letters_1 = {'t', 'u', 'o', 'r', 'i', 'a', 'l'}
letters_2 = {'p', 'o', 'i', 'n', 't'}
letters_3 = {'t', 'u'}
# Intersection of three sets
result = letters_1.intersection(letters_2, letters_3)
print("Intersection of all three sets:", result)
Intersection of all three sets: {'t'}
Example 3: Using & Operator
You can also use the & operator as an alternative to intersection() ?
numbers_1 = {1, 2, 3, 4, 5}
numbers_2 = {4, 5, 6, 7, 8}
# Using intersection() method
method_result = numbers_1.intersection(numbers_2)
print("Using intersection():", method_result)
# Using & operator
operator_result = numbers_1 & numbers_2
print("Using & operator:", operator_result)
Using intersection(): {4, 5}
Using & operator: {4, 5}
How It Works
The interpreter searches for common elements across all provided sets and returns them as a new set. The original sets remain unchanged during this operation.
Conclusion
The intersection() method finds common elements between sets, returning a new set with shared values. Use it when you need to identify overlapping data between multiple collections.
