intersection(): checking similarities between Sets in Python

The intersection() method checks the intersection of items between two or more sets, that is, items that exist in all sets.

In the example below both sets together have the item ‘bmw’.

car_brands_set_one = {'bmw', 'mclaren', 'ferrari'}

car_brands_set_two = {'honda', 'bmw', 'ford'}

car_brands_set_intersection = car_brands_set_one.intersection(car_brands_set_two)

print(car_brands_set_intersection)
{'bmw'}

When comparing more than two sets, they have to be separated by commas.

In this example, all four sets have ‘bmw’ and ‘ford’ in common.

car_brands_set_one = {'bmw', 'mclaren', 'ferrari', 'ford'}

car_brands_set_two = {'honda', 'bmw', 'ford'}

car_brands_set_three = {'bmw', 'toyota', 'jeep', 'ford'}

car_brands_set_four = {'bmw', 'ford', 'hyundai'}

car_brands_set_intersection = car_brands_set_one.intersection(
car_brands_set_two, 
car_brands_set_three, 
car_brands_set_four
)

print(car_brands_set_intersection)
{'ford', 'bmw'}

To learn more about Sets, read this post Python Set: a quick reference