Assume that S
and T
are assigned sets. Without using the join operator |
, how can I find the union of the two sets? This, for example, finds the intersection:
S = {1, 2, 3, 4}
T = {3, 4, 5, 6}
S_intersect_T = { i for i in S if i in T }
So how can I find the union of two sets in one line without using |
?
Assuming you also can't use s.union(t)
, which is equivalent to s | t
, you could try
>>> from itertools import chain
>>> set(chain(s,t))
set([1, 2, 3, 4, 5, 6])
Or, if you want a comprehension,
>>> {i for j in (s,t) for i in j}
set([1, 2, 3, 4, 5, 6])
You can do union
or simple list comprehension
[A.add(_) for _ in B]
A would have all the elements of B
You could use or_
alias:
>>> from operator import or_
>>> from functools import reduce # python3 required
>>> reduce(or_, [{1, 2, 3, 4}, {3, 4, 5, 6}])
set([1, 2, 3, 4, 5, 6])
If you are fine with modifying the original set (which you may want to do in some cases), you can use set.update()
:
S.update(T)
The return value is None
, but S
will be updated to be the union of the original S
and T
.
If by join you mean union, try this:
set(list(s) + list(t))
It's a bit of a hack, but I can't think of a better one liner to do it.
Suppose you have 2 lists
A = [1,2,3,4]
B = [3,4,5,6]
so you can find A
Union B
as follow
union = set(A).union(set(B))
also if you want to find intersection and non-intersection you do that as follow
intersection = set(A).intersection(set(B))
non_intersection = union - intersection
You can use union method for sets: set.union(other_set)
Note that it returns a new set i.e it doesn't modify itself.
You can just unpack both sets into one like this:
>>> set_1 = {1, 2, 3, 4}
>>> set_2 = {3, 4, 5, 6}
>>> union = {*set_1, *set_2}
>>> union
{1, 2, 3, 4, 5, 6}
The *
unpacks the set. Unpacking is where an iterable (e.g. a set or list) is represented as every item it yields. This means the above example simplifies to {1, 2, 3, 4, 3, 4, 5, 6}
which then simplifies to {1, 2, 3, 4, 5, 6}
because the set can only contain unique items.
Source: Stackoverflow.com