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.


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
# Performing union operation and storing result in new set C
#Printing a result
print("AUB is ",C)
# If no parameter is passed it returns a set itself
#Printing a result
print("No parameter passed in union",D)


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)


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
# Using union method
# Printing a Set
print ("Result of union ",c)


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


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.


Happy Learning πŸ™‚