Skip to content

Python set union method | Example code

  • by

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

In 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)

print(z)

Output:

Python set union method

Multiple set union

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

res = x.union(y, z)

print(res)

Output:

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

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

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