Python set union method | Example code

The Python set union() method is used to get distinct elements from all the sets. The union() method returns a set that contains all items from the original set and all items from the specified set(s).

set.union(set1, set2...) 

Python set union example

Simple example code the union() method returns a new set with elements from the set and all other argument sets but if the argument is not passed it returns a shallow copy of the set.

x = {"A", "B", "C"}
y = {"G", "M", "A"}

z = x.union(y)



Python set union method

Multiple set union

x = {"a", "b", "c"}
y = {"c", "d", "a"}
z = {"a", "d"}

res = x.union(y, z)



{‘c’, ‘a’, ‘b’, ‘d’}

Do comment if you have any doubts and suggestions on this python set topic.

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.