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?
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.
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.
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.
∪ 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}.
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)
>>> l = [set([1, 2, 3]), set([3, 4, 5]), set([0, 1])]
>>> set.union(*l)
set([0, 1, 2, 3, 4, 5])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With