how to get the union of two sets in python

To get the union of two sets in Python, you can use the union() method or the '|' operator by passing the second set as a parameter. Here's an example:

main.py
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)  # using union() method
print(union_set)  # Output: {1, 2, 3, 4, 5}

union_set = set1 | set2  # using '|' operator
print(union_set)  # Output: {1, 2, 3, 4, 5}
222 chars
8 lines

Both methods return a new set containing all the elements from both sets without any duplicates.

gistlibby LogSnag