Skip to content

Union of two sets in Python | Example code

  • by

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)



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 is Set Union 2 sets Using the | Operator

set1 = {'A', 'B'}

set2 = {'C', 'B'}

new_set = set1 | set2


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

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

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading