Home > Net >  How can python merges a list of sets and return them as a set?
How can python merges a list of sets and return them as a set?

Time:10-30

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?

CodePudding user response:

You can use unpacking with set.union for a clean one-liner.

>>> set.union(*set_list)
{1, 2, 3, 4, 5, 6, 8}

CodePudding user response:

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}

CodePudding user response:

You can iterate over the list and create a union of all sets:

new_set = set()
for i in set_list:
    new_set =  set.union(new_set, i)
print(new_set)

Output:

{1, 2, 3, 4, 5, 6, 8}

CodePudding user response:

You might do that using comprehension as follows

set_list = [{1, 2, 3}, {4, 5, 1, 6}, {2, 3, 6}, {1, 5, 8}]
final_set = set(elem for sub in set_list for elem in sub)
print(final_set)

output

{1, 2, 3, 4, 5, 6, 8}

Explanation: this is simple adaptation of list-of-lists flattener comprehension which can be used as sets are iterable.

  • Related