Python: Union of Sets

Union of two given sets is the smallest set which contains all the elements of both the sets. It return a set that contains all items from the original set, and all items from the specified sets.

If an item is present in more than one set, the result will contain only one appearance of this item.

Syntax:

set.union(set1, set2...)

Parameters:

It takes any number of sets, which can be given.

Returns:

  • It returns a set, which has the union of all sets(set1, set2, set3…) with set1.
  • It returns a copy of set1 only if no parameter is passed.

Example:

A = {1,2,3}
B = {4,5}
C = {6,7,8}

print('A U B =', A.union(B))
print('A U C =',A.union(C))
print('B U C =',B.union(C))
print('A U B U C =',A.union(B,C))

Output:

A U B = {1, 2, 3, 4, 5}
A U C = {1, 2, 3, 6, 7, 8}
B U C = {4, 5, 6, 7, 8}
A U B U C = {1, 2, 3, 4, 5, 6, 7, 8}
Tags