Skip to content

Python set union operator | Example code

  • by

Python set union operator returns a set that contains all items from the original set and all items from the specified set. The set union operator is denoted by the vertical bar | or by using the union() method.

new_set = set1 | set2

An example set union operator in Python

Simple example code union of sets using the | operator.

A = {'a', 'c', 'd'}
B = {'c', 'd', 0}

print('A U B =', A | B)


Python set union operator

Another example

s1 = {'Python', 'Java'}
s2 = {'C#', 'Java'}

s = s1 | s2


Output: {‘Java’, ‘C#’, ‘Python’}

Using the union() method:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.union(set2)
print(result)  # Output: {1, 2, 3, 4, 5}

Both the | operator and the union() method perform the same operation of combining the elements of two sets while eliminating duplicates.

Note: Use the union() method to accept one or more iterables, convert the iterables to sets, and performs the union.

Comment if you have any doubts or suggestions on this Python set union 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

Your email address will not be published. Required fields are marked *