223

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

5
  • 1
    do you need to union? If yes then you can do s.union(t) Commented Jul 2, 2013 at 15:12
  • 97
    Why can't you use |? Commented Sep 7, 2014 at 20:45
  • 5
    Any generic reason not to use | ?
    – matanox
    Commented Mar 28, 2019 at 17:46
  • 7
    One reason might be passing a set operation as a function argument. Imagine a function, something like: def apply_set_operation(a, b, set_operation). When calling this function, I'd prefer apply_set_operation(a, b, set.union) to apply_set_operation(a, b, set.__or__)
    – bsa
    Commented May 20, 2019 at 1:11
  • What's the use case for a function to abstract set operations? Why not just do a | b instead of calling a function to do that? Commented Jan 23, 2021 at 0:13

10 Answers 10

382

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.

9
  • 77
    However, | can modify the variable inline: set_a |= set_b
    – jorgenkg
    Commented Feb 17, 2016 at 19:13
  • 14
    @jorgenkg same as: set_a = set_a.union(set_b). If you mean "in-place", neither will do that, both create a new set
    – nitely
    Commented Nov 10, 2016 at 2:22
  • 3
    @jorgenkg it still creates a new set and replaces the reference.
    – Alvaro
    Commented Jan 25, 2017 at 21:12
  • 3
    @Alvaro @nitely according to a simple test: a = set((1, 2, 3,)); b = set((1, 3, 4,)); id_a = id(a); a |= b; assert id_a == id(a), @jorgenkg is right - variable a is modified inline. Am I missing something?
    – johndodo
    Commented Jan 7, 2018 at 10:06
  • 4
    Nope, doesn't look like it: a = set((1, 2, 3,)); b = set((1, 3, 4,)); c = a; a |= b; assert id(c) == id(a). Even if a was destroyed, c wouldn't have been. Also, c is now set([1, 2, 3, 4]), so @jorgenkg's comment is correct.
    – johndodo
    Commented Jan 19, 2018 at 10:07
62

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])
1
  • 11
    love this approach, more functional, and could be applied to 2 or more sets.
    – Colin Su
    Commented Apr 23, 2014 at 1:38
58

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.

30

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

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.

3
  • 2
    What does the * do in line 3?
    – altabq
    Commented Apr 14, 2020 at 14:32
  • @altabq He answers what starred expressions are in the answer. Also try playing with it in the REPL. See what print(set_1) vs. print(*set_1) looks like. Also this may give you more info: stackoverflow.com/questions/12555627/…
    – Aaron Bell
    Commented Jan 1, 2021 at 2:52
  • Thanks @aaron-bell, the answer was edited after I posted my comment to include the explanation.
    – altabq
    Commented Jan 12, 2021 at 16:34
17

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.

3
  • set(list(s) + list(t)) will give you the same the result if you will do a union. Commented Jul 2, 2013 at 15:17
  • I'm aware, but it looks like he was trying to avoid using built in python functions, otherwise he would have just used the | operator. Commented Jul 2, 2013 at 15:19
  • list and set are built in python functions Commented Aug 9, 2018 at 0:27
14

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
6

You can do union or simple list comprehension

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

A would have all the elements of B

1
  • 2
    using list comprehension for side effects and with anonymous param is super bad practice. Commented Sep 5, 2019 at 17:33
5

If you want to join n sets, the best performance seems to be from set().union(*list_of_sets), which will return a new set.

Thus, the usage might be:

s1 = {1, 2, 3}
s2 = {2, 3, 4}
s3 = {4, 5, 6}

s1.union(s2, s3) # returns a new set
# Out: {1, 2, 3, 4, 5, 6}
s1.update(s2, s3) # updates inplace

Adding to Alexander Klimenko's answer above, I did some simple testing as shown below. I believe the main takeaway is that it seems like the more random the sets are, the bigger the difference on performance.

from random import randint

n = 100

generate_equal = lambda: set(range(10_000))
generate_random = lambda: {randint(0, 100_000) for _ in range(10_000)}

for l in [
    [generate_equal() for _ in range(n)],
    [generate_random() for _ in range(n)]
]:
    %timeit set().union(*l)
    %timeit reduce(or_, l)
Out:
  # equal sets: 69.5 / 23.6 =~ 3
  23.6 ms ± 658 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
  69.5 ms ± 2.57 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
  # random sets: 438 / 78.7 =~ 5.6
  78.7 ms ± 1.48 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
  438 ms ± 20.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Therefore, if you want to update inplace, the best performance comes from set.update method, as, performance wise, s1.update(s2, s3) = set().union(s2, s3).

0

It seems to me you are looking for an explicit CONDITION to determine which elements are taken. In that case I can offer these one-liners:

  • S_union_T = [i for SET, OTHER_SET, FIRST in zip([S, T], [T, S], [True, False]) for i in SET if FIRST or (i not in OTHER_SET)]

And, another version of the same idea:

  • S_union_T = [i for SET,OTHER_SET in zip([S, T], [[], S]) for i in SET if i not in OTHER_SET]

Breakdown: Basically, we want all items, but uniquely, i.e. only once. this is achieved here by taking the set Difference (items that are in one set but NOT the other) and also taking (ONCE!) the set intersection. The Difference is achieved by iterating over items in SET and conditioning on NOT being in OTHE_SET, while alternating sets SET and OTHER_SET to be first S and T, respectively, and then T and S. But that would yield just the Difference. We need to add the intersection. In order to do that we will drop the condition in the first go, so ALL elements of S will be taken, regardless if they are in T. So the idea is to take all items from first set, and then only items from second set that are (CONDITION): not in the first set.

The first version has this CONDITION written explicitly, by adding a third parameter FIRST and conditioning on it. Items are taken either if they are from the FIRST set, or if they are not in the OTHER_SET. The second version sneaks this condition in by 'cheating'. It feeds an empty set (or list) where T should have been, as the OTHER_SET, so now elements from S are taken if they are not in an empty set (which is always True).

I hope this is clear enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.