How to join two sets in one line without using "|"

189

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 |?

This question is tagged with python set

~ Asked on 2013-07-02 15:05:51

The Best Answer is


336

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.

~ Answered on 2013-07-02 15:57:03


50

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])

~ Answered on 2013-09-26 11:51:35


Most Viewed Questions: