Python Set union() Method
The set.union()
method returns a new set with distinct elements from all the given sets.
Syntax:
A.union(*other_sets)
Parameters:
other_seats: Required. The one or more sets separated by a comma.
Return type:
Returns a set, which is a union of all the sets.
The following example demonstrates the set.union()
method.
nums1 = {1, 2, 2, 3, 4, 5}
nums2 = {4, 5, 6, 7, 7, 8}
distinct_nums = nums1.union(nums2)
print("The union of two sets is: ", distinct_nums)
The union of two sets is: {1, 2, 3, 4, 5, 6, 7, 8}
The set.union()
method on multiple sets.
nums1 = {1, 2, 2, 3, 4, 5}
nums2 = {4, 5, 6, 6, 7, 8, 8}
nums3 = {7, 8, 9, 10}
distinct_nums = nums1.union(nums2, nums3)
print("The union of three sets is: ", distinct_nums)
The union of the sets is: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
The |
operator can also be used to perform the union operation.
nums1 = {1, 2, 2, 3, 4, 5}
nums2 = {4, 5, 6, 6, 7, 8, 8}
nums3 = {7, 8, 9, 10}
distinct_nums = nums1 | nums2 | nums3
print("The union of three sets is: ", distinct_nums)
The union of three sets is: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}