27 of 151 menu

The intersection method

The intersection method performs the intersection of several sets, as a result of which it returns a new set with common elements for the specified sets. In the method parameter, we pass the set for which we want to find out the common elements.

Syntax

set.intersection(set with which we want to find common elements)

Example

Let's apply the intersection method to get the common elements of two sets:

st1 = {'a', 'b', 'c'} st2 = {'e', 'f', 'c', 'a'} res = st1.intersection(st2) print(res)

Result of code execution:

{'c', 'a'}

Example

The intersection method also has a short form:

st1 = {'a', 'b', 'c'} st2 = {'e', 'f', 'c', 'a'} res = st1 & st2 print(res)

Result of code execution:

{'c', 'a'}

See also

  • method union,
    which unites sets
  • method difference,
    which returns the differences between sets
byenru