Python Set intersection() Method

The intersection() method returns a new set containing elements that are common to all sets involved in the operation.

Syntax

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

Or using the & operator

set1 & set2 & set3

Parameters

set2, set3, ...: One or more sets (or other iterables such as lists, or tuples) to compare for common elements.

Return Value

Returns a new set containing only the elements common to all sets. The original sets remain unchanged.

Example: Intersection of two sets

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

result = a.intersection(b)
print(result) # Output: {3, 4}

Example: Intersection of multiple sets

You can pass multipe sets, separated by commas, as arguments to the intersection() method.

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
c = {3, 6, 9, 11}

result = a.intersection(b, c)
print(result) # Output: {3}

Example: Intersection with other data types

You can also pass other iterables, such as lists or tuples, to the intersection() method.

a = {1, 2, 3, 4}
b = [3, 4, 5, 6]
c = (2, 3, 4, 5)

result = a.intersection(b, c)
print(result) # Output: {3, 4}

The & Operator

The & operator offers a shorthand way to perform set intersection.

For example:

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
c = {3, 6, 9, 11}

result = a & b & c
print(result) # Output: {3}

Also Read:

Python Set intersection_update() Method