218

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) Jul 2, 2013 at 15:12
  • 93
    Why can't you use |? Sep 7, 2014 at 20:45
  • 4
    Any generic reason not to use | ?
    – matanster
    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
    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? Jan 23, 2021 at 0:13

9 Answers 9

372

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
  • 74
    However, | can modify the variable inline: set_a |= set_b
    – jorgenkg
    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
    Nov 10, 2016 at 2:22
  • 3
    @jorgenkg it still creates a new set and replaces the reference.
    – Alvaro
    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
    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
    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
    Apr 23, 2014 at 1:38
57

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
    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
    Jan 1, 2021 at 2:52
  • Thanks @aaron-bell, the answer was edited after I posted my comment to include the explanation.
    – altabq
    Jan 12, 2021 at 16:34
18

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. 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. Jul 2, 2013 at 15:19
  • list and set are built in python functions 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. Sep 5, 2019 at 17:33
4

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

Your Answer

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

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