The union()
method merges as many sets as you want and returns a new set as a result.
The items in the new set are unique, meaning no repetitions.
In the example below both sets together should equal 6 items, but ‘bmw’ is present in both of them, so only one remains and the resulting set has only 5 items.
car_brands_set_one = {'bmw', 'mclaren', 'ferrari'}
car_brands_set_two = {'honda', 'bmw', 'ford'}
car_brands_set_merged = car_brands_set_one.union(car_brands_set_two)
print(car_brands_set_merged)
{'bmw', 'mclaren', 'ford', 'honda', 'ferrari'}
When merging more than two sets, they have to be separated by commas.
car_brands_set_one = {'bmw', 'mclaren', 'ferrari'}
car_brands_set_two = {'honda', 'bmw', 'ford'}
car_brands_set_three = {'mclaren', 'toyota', 'jeep'}
car_brands_set_four = {'suzuki', 'ford', 'hyundai'}
car_brands_set_merged = car_brands_set_one.union(
car_brands_set_two,
car_brands_set_three,
car_brands_set_four
)
print(car_brands_set_merged)
{'bmw', 'hyundai', 'honda',
'jeep', 'suzuki', 'toyota',
'mclaren', 'ford', 'ferrari'}
To learn more about Sets, read this post Python Set: a quick reference