Languages
[Edit]
EN

Python - join two sets

0 points
Created by:
Isaiah89
661

In this article, we would like to show you how to join two sets in Python.

1. Using union() method

In this example, we use union() method to create a new set with all items from the two existing sets.

my_set1 = {'A', 'B'}
my_set2 = {'C', 'D'}

my_set3 = my_set1.union(my_set2)

print(my_set3)  # {'C', 'A', 'B', 'D'}

Output:

{'C', 'A', 'B', 'D'}

2. Using update() method

In this example, we use update() method to add the items from my_set2 to my_set1.

my_set1 = {'A', 'B'}
my_set2 = {'C', 'D'}

my_set1.update(my_set2)

print(my_set1)  # {'B', 'A', 'D', 'C'}

Output:

{'B', 'A', 'D', 'C'}

Note:

Both presented methods exclude duplicate elements.

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Python - set (popular problems)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join