Skip to content

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.

The | operator can be used to combine two sets and create a new set that contains all the unique elements from both sets.

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’}

Bitwise OR operation:

The | operator can also be used to perform a bitwise OR operation between two integers. It compares the binary representation of each corresponding bit and sets the result bit to 1 if at least one of the bits is 1. Here’s an example:

a = 10  # Binary: 1010
b = 6   # Binary: 0110
result = a | b
print(result)  # Output: 14 (Binary: 1110)

Do comment if you have any doubts or suggestions on this Python operator 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