Python union operator with Example code

  • by

Union means combining data that contains elements from the set and all others. There is a union method used for it but you can also the | Union operator.

new_set = set1 | set2

Note: the union operator ( | ) only allows sets, not iterables like the union() method.

Example union operator in Python

Simple example code.

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

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

Output:

Python union operator

Another example

Union sets using the | operator. The set union operator (|) returns a new set that consists of distinct elements from both set1 and set2.

set1 = {'Python', 'Java'}
set2 = {'C#', 'Java'}

res = set1 | set2

print(res)

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

Do comment if you have any doubts and suggestions on this Python operator topic.

Note: IDE: PyCharm 2021.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 *

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