Python Set union() Method

Python provides the set type in order to implement mathematical sets. The set contains single or multiple items where every item is unique. Like mathematical sets, the union operation can be executed for two or more sets. The union() method of the set is used for union operation. In this tutorial, we examine how to implement union operations for Python sets.

Union Two Sets

Every set provides the union() method, where another set can be provided as parameters, and these two sets, are unioned together.

s1 = {"a","b","c"}

s2 = {"a","d","e"}

s = s1.union(s2)

print(s)
{"a","b","c","d","e"}

Union Multiple Sets

The union() method can be used for multiple sets. Every set is provided as a parameter by separating their commas.

s1 = {"a","b","c"}

s2 = {"a","d","e"}

s3 = {"b","f","g"}

s = s1.union(s2,s3)

print(s)
{"a","b","c",,"d","e","f","g"}

Union Sets Using Pipe Operator

Even union() method is used for mathematical union operation alternatively the pipe or | can be used to union two or more sets. Every set we want to union is separated with the pipe or | operator.

s1 = {"a","b","c"}

s2 = {"a","d","e"}

s = s1 | s2

print(s)
{"a","b","c","d","e"}

Leave a Comment