Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

set

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?

like image 883
V.Nouri Avatar asked Oct 26 '25 19:10

V.Nouri


2 Answers

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

>>> set().union(*set_list)
{1, 2, 3, 4, 5, 6, 8}
like image 104
Troll Avatar answered Oct 29 '25 09:10

Troll


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}
like image 35
Abdul Niyas P M Avatar answered Oct 29 '25 07:10

Abdul Niyas P M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!