Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking the union of sets

Tags:

python

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?

like image 929
Randomblue Avatar asked Feb 25 '12 23:02

Randomblue


People also ask

How do you take unions in a set?

The union of two sets is a set containing all elements that are in A or in B (possibly both). For example, {1,2}∪{2,3}={1,2,3}. Thus, we can write x∈(A∪B) if and only if (x∈A) or (x∈B). Note that A∪B=B∪A.

What is the formula for union of sets?

ii) Union of two sets:n(A ∪ B) = n(A) + n(B) – n(A ∩ B) Simply, the number of elements in the union of set A and B is equal to the sum of cardinal numbers of the sets A and B, minus that of their intersection.

What is a ∩ B in sets?

The intersection operation is denoted by the symbol ∩. The set A ∩ B—read “A intersection B” or “the intersection of A and B”—is defined as the set composed of all elements that belong to both A and B.

What does ∩ and ∪ mean in math?

∪ The symbol ∪ means union. Given two sets S and T, S ∪ T is used to denote the set {x|x ∈ S or x ∈ T}. For example {1,2,3}∪{3,4,5} = {1,2,3,4,5}. ∩ The symbol ∩ means intersection. Given two sets S and T, S ∩ T is used to denote the set {x|x ∈ S and x ∈ T}.


2 Answers

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)
like image 146
Justin Peel Avatar answered Sep 30 '22 03:09

Justin Peel


>>> l = [set([1, 2, 3]), set([3, 4, 5]), set([0, 1])]
>>> set.union(*l)
set([0, 1, 2, 3, 4, 5])
like image 43
Praveen Gollakota Avatar answered Sep 30 '22 02:09

Praveen Gollakota