Taking the union of sets

I have a list of l sets. To take the union of all the sets in l , I do:

 union = set() for x in l: union |= x 

I have a feeling that there is a more economical / functional way of writing this. Can i improve this?

+4
source share
4 answers

Here is how I would do it (some corrections according to the comments):

 union_set = set() union_set.update(*l) 

or

 union_set = set.union(*l) 
+9
source
 >>> l = [set([1, 2, 3]), set([3, 4, 5]), set([0, 1])] >>> set.union(*l) set([0, 1, 2, 3, 4, 5]) 
+5
source

If you are looking for a functional approach, there is a bit more traditional than reduce() :

 >>> reduce(set.union, [ set([1,2]), set([3,4]), set([5,6]) ]) set([1, 2, 3, 4, 5, 6]) 

In Python 3.0, reduce can be found in the functools module ; in 2.6 and 2.7, it exists both in functools and (as in older interpreters).

+4
source
 union = reduce(set.union, l) 

In Python 2.x, reduce is built-in. In 3.x, it is in the functools module.

+3
source

Source: https://habr.com/ru/post/1398428/


All Articles