Join multiple sets in Python
This post will discuss how to join multiple sets in Python.
1. Using itertools.chain() function
The itertools module provides several useful functions to create iterators for efficient looping. You can use its chain() function to join two or more sets together, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import itertools if __name__ == '__main__': x = {1, 3} y = {5} z = {7, 9} s = set(itertools.chain(x, y, z)) print(s) # {1, 3, 5, 7, 9} |
2. Using Iterable Unpacking Operator
With Python 3.5, you can use the * iterable unpacking operator for joining multiple sets. Here’s what the code would look like:
|
1 2 3 4 5 6 7 8 9 10 |
if __name__ == '__main__': x = {1, 3} y = {5} z = {7, 9} s = {*x, *y, *z} print(s) # {1, 3, 5, 7, 9} |
3. Using union() function
The union() function appends all the items from a set to another set. You can use it for joining multiple sets, as shown below:
|
1 2 3 4 5 6 7 8 9 10 |
if __name__ == '__main__': x = {1, 3} y = {5} z = {7, 9} s = set().union(x).union(y).union(z) print(s) # {1, 3, 5, 7, 9} |
That’s all about joining multiple sets in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)