I have a list of sets like this:
set_list = [{1, 2, 3}, {4, 5, 1, 6}, {2, 3, 6}, {1, 5, 8}]
Now I want to merge all of the sets together and return a set of all sets like this:
final_set = {1, 2, 3, 4, 5, 6, 8}
I have used this code but it is not working correctly:
tmp_list = []
final_set = set(tmp_list.append(elem) for elem in set_list)
What should I do?
You can use unpacking with set().union for a clean one-liner.
>>> set().union(*set_list)
{1, 2, 3, 4, 5, 6, 8}
You can use reduce function from functools module.
>>> from functools import reduce
>>> set_list = [{1,2,3}, {4,5,1,6}, {2,3,6}, {1,5,8}]
>>> reduce(lambda x, y: x | y, set_list)
{1, 2, 3, 4, 5, 6, 8}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With