Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union of multiple sets in a list [duplicate]

This is my code.

s = set()
for x in [ {1,2}, {3,4}, {5,1} ]:
    s |= x

It returns set([1, 2, 3, 4, 5]).

Is it possible to use set comprehension in such a case? How can I write it shorter?

like image 262
ndsvw Avatar asked Oct 27 '25 18:10

ndsvw


2 Answers

set.union

set.union(*[{1,2}, {3,4}, {5,1}])
# {1, 2, 3, 4, 5}

Why do you need a loop at all? Use set.union, it lets you compute the union of more than two sets (containers) at a time. I say "containers", because the second (and onwards) arguments need not be sets at all.

set.union(*[{1,2}, [3,4], [5,1]])
# {1, 2, 3, 4, 5}

The first, however, needs to be. Alternatively,

set().union(*[[1,2], [3,4], [5,1]])
# {1, 2, 3, 4, 5}

When calling union on a set object (and not the class), none of the arguments need be sets.


functools.reduce

from functools import reduce

reduce(set.union, [{1,2}, {3,4}, {5,1}])
# {1, 2, 3, 4, 5}

This performs a pairwise reduction, accumulating a result. Not nearly as good as the first option, however.

like image 164
cs95 Avatar answered Oct 29 '25 08:10

cs95


If you really want a set comprehension here:

lst = [{1,2}, {3,4}, {5,1}]
{elem for set_ in lst for elem in set_}
like image 45
internet_user Avatar answered Oct 29 '25 08:10

internet_user



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!