Python Set Union

python-set-union-method-ipcisco-1

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


 

python-set-union-method-ipcisco-1

 

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'}

 

 

python-set-union-method-ipcisco-2

 

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.

 

gokhan-kosem-instructor-ipcisco

Gokhan Kosem is a Network Engineer, Instructor and the Founder of IPCisco.com with 15+ years of experience in Cisco, Nokia, Huawei, Juniper, Linux, Service Provider Networks, Routing and Switching technologies.

He has worked on the backbone networks of major service providers and network vendors including Nortel, Alcatel-Lucent (Nokia) and has extensive hands-on experience with Cisco, Huawei, Juniper and Nokia networking technologies.

He has trained thousands of networking students worldwide through IPCisco.com, Udemy, books, labs, quizzes, and educational content across multiple social media platforms.

IPCisco.com | Best Route to Your Dreams

Back to: Python Programming Course > Python Sets

Leave a Reply

Your email address will not be published. Required fields are marked *

ipcisco gold membership

Python Programming Course

Collapse
Expand