4

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?

1
  • "it is not working correctly": Please provide details. Commented Oct 30, 2021 at 7:51

4 Answers 4

16

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

>>> set().union(*set_list)
{1, 2, 3, 4, 5, 6, 8}
Sign up to request clarification or add additional context in comments.

2 Comments

This "accidentally" works by sending in the first element of set_list as "self". It is better to use set().union(*set_list) so that you still get the correct result for set_list = [] instead of an exception.
@wim I have changed it to set().union. Thank you for pointing it out!
3

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}

Comments

2

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}

1 Comment

Note that as you do union in-place you might use .update without need to assignment, i.e. instead of new_set = set.union(new_set, i) do new_set.update(i)
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.