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.

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

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

Do comment if you have any doubts or suggestions on this Python set union code.

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.