How to join two sets on the same line without using "|"

Suppose that S and T are assigned sets. Without using a join operator | how can i find a union of two sets? This, for example, finds an 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 on the same line without using | ?

+139
python set
Jul 02 '13 at 15:05
source share
8 answers

You can use union method for sets: set.union(other_set)

Note that it returns a new set of ie, it does not modify itself.

+256
Jul 02 '13 at 15:57
source share

Sorry, why can't we use the join operator again?

 >>> set([1,2,3]) | set([4,5,6]) set([1, 2, 3, 4, 5, 6]) 
+71
Jan 28 '15 at 19:39
source share

You can use the alias or_ :

 >>> 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]) 
+38
Sep 26 '13 at 11:51 on
source share

Assuming you also can't use s.union(t) , which is equivalent to s | t s | t you can try

 >>> from itertools import chain >>> set(chain(s,t)) set([1, 2, 3, 4, 5, 6]) 

Or if you want to understand

 >>> {i for j in (s,t) for i in j} set([1, 2, 3, 4, 5, 6]) 
+20
Jul 02 '13 at 15:12
source share

If everything is fine with changing the original set (which may be necessary 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

+17
Mar 06 '18 at 19:52
source share

If you mean join by join, try the following:

 set(list(s) + list(t)) 

It’s a little hack, but I can’t think of a better liner for this.

+13
Jul 02 '13 at 15:13
source share

Suppose you have 2 lists

  A = [1,2,3,4] B = [3,4,5,6] 

to find A Union B as follows

  union = set(A).union(set(B)) 

also, if you want to find the intersection and non-intersection, you do this by following

  intersection = set(A).intersection(set(B)) non_intersection = union - intersection 
+9
Sep 01 '14 at 11:04 on
source share

You can do union or a simple list comprehension

 [A.add(_) for _ in B] 

A will have all the elements of B

+5
May 13 '15 at 13:02
source share



All Articles