2

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?

cs95
  • 379,657
  • 97
  • 704
  • 746
hardfork
  • 2,470
  • 1
  • 23
  • 43

2 Answers2

10

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.

Community
  • 1
  • 1
cs95
  • 379,657
  • 97
  • 704
  • 746
  • 1
    Instead of `{1, 2}.union(*[[3,4], [5,1]])` you can also use `set().union(*[{1,2}, [3,4], [5,1]])`. – Aran-Fey Apr 13 '18 at 19:41
4

If you really want a set comprehension here:

lst = [{1,2}, {3,4}, {5,1}]
{elem for set_ in lst for elem in set_}
internet_user
  • 3,149
  • 1
  • 20
  • 29