English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial básico Python

Controle de fluxo Python

Funções do Python

Tipos de Dados do Python

Operações de arquivos Python

Objetos e classes Python

Data e hora Python

Conhecimentos avançados Python

Manual de referência Python

Métodos e exemplos de uso da função intersection() de conjuntos Python

Métodos de Conjunto do Python

The intersection() method will return a new set containing the elements common to all sets.

The intersection of two or more sets is the set of elements common to all sets. For example:

A = {1, 2, 3, 4}
B = {2, 3, 4,  9}
C = {2, 4, 9 10}
Then,
A∩B = B∩A = {2, 3, 4}
A∩C = C∩A = {2, 4}
B∩C = C∩B = {2, 4, 9}
A∩B∩C = {2, 4}

The syntax of intersection() in Python is:

A.intersection(*other_sets)

intersection() parameters

intersection() allows an arbitrary number of parameters (sets).

Note: *Is not part of the syntax. Used to indicate that this method allows an arbitrary number of parameters.

Intersection() return value

The intersection() method returns the intersection of set A with all sets passed as parameters.

If no parameters are passed to intersection(), it will return a shallow copy of the set (A).

Example1: How does intersection() work?

A = {2, 3, 5, 4}
B = {2, 5, 100}
C = {2, 3, 8, 9, 10}
print(B.intersection(A))
print(B.intersection(C))
print(A.intersection(C))
print(C.intersection(A, B))

When running the program, the output is:

{2, 5}
{2}
{2, 3}
{2}

More examples

A = {100, 7, 8}
B = {200, 4, 5}
C = {300, 2, 3}
D = {100, 200, 300}
print(A.intersection(D))
print(B.intersection(D))
print(C.intersection(D))
print(A.intersection(B, C, D))

When running the program, the output is:

{100}
{200}
{300}
set()

You can also use the & operator to find the intersection of sets

Example3: Use the & operator to set the intersection

A = {100, 7, 8}
B = {200, 4, 5}
C = {300, 2, 3, 7}
D = {100, 200, 300}
print(A & C)
print(A & D)
print(A & C & D)
print(A & B & C & D)

When running the program, the output is:

{7}
{100}
set()
set()

Métodos de Conjunto do Python