Python set Method - union()
The union()
method in Python sets returns a new set that contains all the distinct elements from two or more sets. In other words, it returns the set of all elements that are present in any of the sets.
The syntax for the union()
method is as follows:
set1.union(set2, set3, ...)ruoSce:www.theitroad.com
Here, set1
, set2
, set3
, etc. are the sets that we want to combine.
Example:
# Creating two sets set1 = {1, 2, 3} set2 = {3, 4, 5} # Combining the two sets using the union() method result_set = set1.union(set2) print(result_set) # Output: {1, 2, 3, 4, 5}
In the above example, the union()
method is used to combine set1
and set2
. Since set1
contains the elements 1
, 2
, and 3
, and set2
contains the elements 3
, 4
, and 5
, the union of the two sets is the set of all elements that are present in either of the sets, which is {1, 2, 3, 4, 5}
. The result set is printed using the print()
function. Note that the elements 3
is included only once in the result set, since sets do not allow duplicates.