.intersection()
Published May 23, 2022
Contribute to Docs
The .intersection()
method returns a new set with objects that exist inside two or more sets.
Syntax
The following syntaxes can be used:
set.intersection(set1, set2, ..., setN)
setA & setB & setC
- The
.intersection()
method can be called directly againstset
with multiple sets passed as arguments. - Optionally, the
&
operator can be used between setssetA
,setB
, andsetC
where it will return the same result as the.intersection()
method.
Example
In the following example, a set of mutual_friends
is created with the .intersection()
method using two sets of friend groups:
friend_group_1 = {'Juan', 'Mary', 'David', 'Yukiko', 'Alice'}friend_group_2 = {'Yukiko', 'Peter', 'Juan', 'Alice'}mutual_friends = friend_group_1.intersection(friend_group_2)print(mutual_friends)
The output would be:
{'Juan', 'Yukiko', 'Alice'}
Codebyte Example
In the example, a set of trips for the next year is created with the .intersection()
method:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours