Tutorial Study Image

Python union()

The union() function in python helps to return a new set with all elements from given sets without duplication. We can say that a new set with distinct elements. This method can take more than one set of parameters.


A.union(*other_sets) #where * indicate it can take 0 or more arguments.
 

union() Parameters:

The union() function takes sets as its parameter. Python has another way of finding the union that is by using the ' | 'operator.

Parameter Description Required / Optional
other_sets The sets to unify with Required

union() Return Value

This function returns a new set with all elements of the set. If an element exists in both of the sets, one occurrence of the element is taken in the new set.

Input Return Value
if parameter set with distinct elements
no parameter shallow copy of set

Examples of union() method in Python

Example 1: How union() works in Python?


X = {'a', 'c', 'd'}
Y = {'c', 'd', 5 }
Z = {4, 5, 6}

print('X U Y =', X.union(Y))
print('Y U Z =', Y.union(Z))
print('X U Y U Z =', X.union(Y, Z))
print('X.union() =', X.union())
 

Output:


X U Y = {5, 'a', 'd', 'c'}
Y U Z = {4, 5, 6, 'd', 'c'}
X U Y U Z = {4, 5, 6, 'a', 'd', 'c'}
X.union() = {'a', 'd', 'c'}

Example 2: How to find set Union using the | Operator?


X = {'a', 'c', 'd'}
Y = {'c', 'd', 5 }
Z = {4, 5, 6}

print('X U Y =', X| Y)
print('Y U Z =', Y | Z)
print('X U Y U Z =', X | Y | Z)
 

Output:


X U Y = {5, 'a', 'd', 'c'}
Y U Z = {4, 5, 6, 'd', 'c'}
X U Y U Z = {4, 5, 6, 'a', 'd', 'c'}