.intersection()

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 against set with multiple sets passed as arguments.
  • Optionally, the & operator can be used between sets setA, setB, and setC 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:

Edit this page on GitHub

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your feedback form.

Learn Python on Codecademy