In Python, we can easily combine sets by adding two sets together. The easiest way to combine sets is to use |= in your Python code.
a = {0, 1, 2, 3, 4}
b = {4, 5, 6, 7, 8}
a |= b
print(a)
#Output:
{0, 1, 2, 3, 4, 5, 6, 7, 8}
You can also use the set update() function to combine sets in Python.
a = {0, 1, 2, 3, 4}
b = {4, 5, 6, 7, 8}
a.update(b)
print(a)
#Output:
{0, 1, 2, 3, 4, 5, 6, 7, 8}
One other way to join two sets together in Python is with the union() function.
a = {0, 1, 2, 3, 4}
b = {4, 5, 6, 7, 8}
a.union(b)
print(a)
#Output:
{0, 1, 2, 3, 4, 5, 6, 7, 8}
In Python, sets are unordered collections of items. When working with sets, it can be useful to add or remove elements from a set, or combine a set with another set.
We can easily combine two sets together in Python.
There are a number of ways to join two sets together in Python, and the easiest way is to use |=.
Below is an example in Python of how to join two sets with |=
a = {0, 1, 2, 3, 4}
b = {4, 5, 6, 7, 8}
a |= b
print(a)
#Output:
{0, 1, 2, 3, 4, 5, 6, 7, 8}
Combining Two Sets in Python with the set update() Function
Python has a number of great built-in functions which allow us to work with collections easily. The Python set update() function adds items to a set from another set.
With the update() function, we can easily combine two sets.
Below is how to use the update() function in Python to combine two sets into one set.
a = {0, 1, 2, 3, 4}
b = {4, 5, 6, 7, 8}
a.update(b)
print(a)
#Output:
{0, 1, 2, 3, 4, 5, 6, 7, 8}
Joining Two Sets in Python with the set union() Function
One final way to get all of the elements of two sets is to take the union of two sets in Python.
We can use the union() function to take the union of two sets and join them together into one set.
Below is a simple example in Python of how to use the union() function to combine two sets together.
a = {0, 1, 2, 3, 4}
b = {4, 5, 6, 7, 8}
a.union(b)
print(a)
#Output:
{0, 1, 2, 3, 4, 5, 6, 7, 8}
Hopefully this article has been useful for you to learn how to join and combine sets in Python.