Randomblue
Randomblue

Reputation: 116443

Taking the union of sets

I have a list l of 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 there is a more economical/functional way of writing this. Can I improve upon this?

Upvotes: 5

Views: 343

Answers (4)

Justin Peel
Justin Peel

Reputation: 47092

Here's how I would do it (some corrections as per comments):

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

or

union_set = set.union(*l)

Upvotes: 10

Praveen Gollakota
Praveen Gollakota

Reputation: 39010

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

Upvotes: 5

dan04
dan04

Reputation: 91227

union = reduce(set.union, l)

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

Upvotes: 3

Charles Duffy
Charles Duffy

Reputation: 296019

If you're looking for a functional approach, there's little 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) built-in.

Upvotes: 4

Related Questions