Python Set intersection() Method (with Examples)

Python Set intersection() Method: In this tutorial, we will learn about the intersection() method of the set class with its usage, syntax, parameters, return type, and examples. By IncludeHelp Last updated : June 14, 2023

Python Set intersection() Method

The intersection() is an inbuilt method of the set class that is used to get the list of all elements which are common/exist in given sets. To perform the intersection of two or more sets you can use the intersection() method. The method is called with one set and other sets can be passed as parameters of the method.

Syntax

The following is the syntax of intersection() method:

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

Parameter(s):

The following are the parameter(s):

  • set1 – It represents the set to be compared with this set.
  • set2, set3, ... – These are optional sets, we can provide multiple sets to be compared.

Return Value

The return type of this method is <class 'set'>, it returns the set of the elements which are exist in all sets.

Example 1: Use of Set intersection() Method

# declaring the sets
cars_1 = {"Porsche", "Audi", "Lexus"}
cars_2 = {"Porsche", "Mazda", "Lincoln"}

# intersection() method call
x = cars_1.intersection(cars_2)

# printing the sets
print("cars_1:", cars_1)
print("cars_2:", cars_2)
print("x:", x)

Output

cars_1: {'Porsche', 'Audi', 'Lexus'}
cars_2: {'Porsche', 'Lincoln', 'Mazda'}
x: {'Porsche'}

Example 2: Use of Set intersection() Method

# declaring the sets
x = {"ABC", "PQR", "XYZ"}
y = {"ABC", "PQR", "XYZ"}
z = {"DEF", "MNO", "ABC"}

# printing the results
print("x:", x)
print("y:", y)
print("z:", z)

# printing the common elements
print("x.intersection(y,z): ", x.intersection(y,z))
print("y.intersection(x,z): ", y.intersection(x,z))
print("x.intersection(z,y): ", x.intersection(z,y))
print("y.intersection(z,x): ", y.intersection(z,x))
print("z.intersection(x,y): ", z.intersection(x,y))

Output

x: {'PQR', 'ABC', 'XYZ'}
y: {'PQR', 'ABC', 'XYZ'}
z: {'DEF', 'ABC', 'MNO'}
x.intersection(y,z):  {'ABC'}
y.intersection(x,z):  {'ABC'}
x.intersection(z,y):  {'ABC'}
y.intersection(z,x):  {'ABC'}
z.intersection(x,y):  {'ABC'}


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.