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?
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.