Python Set union():

The union() method returns a new set that contains distinct elements from both sets. For example, the Union of set A and B returns all the elements from Sets A and B without repetition.

Method signature

The signature for the union() method is as shown below. Here, It does the union of set A with other sets given in the parameter, and the result is stored in set C.

C=A.union(B1,B2,..)

Method parameters and return type

  • The union() method takes zero or more sets as a parameter.
  • However, The union() function returns a new set, consisting of values from the union of all sets(B1, B2,…) with set A. It returns a copy of set A only if the parameter is absent.

Python Set Union Examples:

Example 1:

In the example given below, let us take a set A and set B with a set of numbers.

#Initializing the Set
A={18,13,48,36,65}
B={22,36,54,13,5}
# Performing union operation and storing result in new set C
C=A.union(B)
#Printing a result
print("AUB is ",C)
# If no parameter is passed it returns a set itself
D=A.union()
#Printing a result
print("No parameter passed in union",D)

Output

AUB is  {65, 36, 5, 13, 48, 18, 54, 22}
No parameter passed in union {48, 65, 18, 36, 13}

Example 2:

In this case, We have a set of students who opted for various optional subjects. Therefore, If we want to find the list of students who had opted for atleast one subject we can get it using the union method.

#Initializing the Set
computer={"Ram", "Jimmy", "Keya"}
sport={"Kim", "Sam","Keya", "Tom"}
pt={"John","Sam", "Ram"}
#Using union method
stu=computer.union(sport, pt)
#Printing a set
print("Students who opted for at least one subject ",stu)

Output

Students who opted for at least one subject  {'Keya', 'Tom', 'Jimmy', 'John', 'Kim', 'Sam', 'Ram'}

Example 3:

For this example, we will demonstrate the union() method on mixed multiple sets.

#Initializing the Set
c1={"Kim",25,8.5}
c2={"Sam",45,10}
c3={"Raj",22,1.5}
c4={"Roy",32,14}
# Using union method
c=c1.union(c2,c3,c4)
# Printing a Set
print ("Result of union ",c)

Output

Result of union  {'Raj', 1.5, 32, 'Kim', 8.5, 10, 45, 14, 'Roy', 22, 25, 'Sam'}

Conclusion

The union() method combines the distinct elements from multiple sets to form a single set. However, it returns the set itself if no parameters are passed.

References

Happy Learning 🙂