We can combine two or more sets together and get a combined set as a result. To do this we use python set union method. We can also use “|” operator to get the same result in Python Programming. To learn this lesson of python, we will give different examples below.
You can also check the other Set Methods of Python Programming.
Let’s shows how to use this method and “|” operator with different examples.
dwarves1 = {"Thorin", "Balin", "Dwalin"}
dwarves2 = {"Gimli", "Bofur", "Thorin"}
dwarves3 = {"Fili", "Kili"}
print(dwarves1.union(dwarves2,dwarves3))
As an output, we will receive the below result. As you can see below, three set has combined and the repeating item, “Thorin” is not written two times in the new combined set.
{'Fili', 'Dwalin', 'Balin', 'Gimli', 'Bofur', 'Thorin', 'Kili'}
You can also check Python Set Remove Methods
Now, let’s use “|” operator to get the same result. Here, we will use this operator between the sets in print function.
dwarves1 = {"Thorin", "Balin", "Dwalin"}
dwarves2 = {"Gimli", "Bofur", "Thorin"}
dwarves3 = {"Fili", "Kili"}
print(dwarves1 | dwarves2 | dwarves3)
{'Fili', 'Dwalin', 'Balin', 'Gimli', 'Bofur', 'Thorin', 'Kili'}
Another example with number set is below:
numbers1 = {1,2,3,4,5,6,7,300}
numbers2 = {1,2,3,100}
numbers3 = {1,2,3,4,5,200}
print(numbers1.union(numbers2,numbers3))
The output of this python code will be:
{1, 2, 3, 4, 5, 6, 7, 100, 200, 300}
We wil get the same result with the below code that we use “|” operator.
numbers1 = {1,2,3,4,5,6,7,300}
numbers2 = {1,2,3,100}
numbers3 = {1,2,3,4,5,200}
print(numbers1|numbers2|numbers3)
{1, 2, 3, 4, 5, 6, 7, 100, 200, 300}
In this lesson, we have learned how to combine python sets with python set union method. We have showed different examples here, you can create your own examples and practice more on this lesson.
Leave a Reply