Union of two sets in Python | Example code

Use the union() method to get the union of two sets in Python. This method returns a new set with distinct elements from all the sets.

set.union(set1, set2...) 

You can specify as single or many sets you want, separated by commas and the result will only be one set. It did not require the passed value should set only, you can use any iterable object.

Example union of two sets in Python

Simple example code gets a new set that contains all items from the original set, and all items from the specified set(s).

set1 = {10, 20, 30}

set2 = {30, 40, 100}

new_set = set1.union(set2)

print(new_set)

Output:

Union of two sets in Python

Note: If the None argument is passed to union(), it returns a shallow copy of the set.

Another example Set Union 2 sets Using the | Operator

set1 = {'A', 'B'}

set2 = {'C', 'B'}

new_set = set1 | set2

print(new_set)

Output: {‘C’, ‘A’, ‘B’}

Do comment if you have any doubts and suggestions on this Python set code.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.