How to join two sets in Python

In this tutorial, we will introduce different methods to join two sets in Python.

  1. A |= B
  2. A.update(B)
  3. A.union(B)
  4. reduce(operator.or_, [A, B])

A |= B to join two sets in Python

A |= B adds all elements of set B to set A.

>>> A = {4, 5, 6, 7}
>>> B = {6, 7, 8, 9}
>>> A |= B
>>> A
{4, 5, 6, 7, 8, 9}

A.update(B) to join two sets in Python

A.update(B) method is identical to A |= B. It modifes set A in place.

>>> A = ["a", "b", "c"]
>>> B = ["b", "c", "d"]
>>> A.update(B)
>>> A
["a", "b", "c", "d"]

A.union(B) to join two sets in Python

A.union(B) returns the union of sets A and B. It doesn’t modify set A in place but returns a new set.

>>> A = {4, 5, 6, 7}
>>> B = {6, 7, 8, 9}
>>> A.union(B)
{1, 2, 3, 4, 5, 6}
>>> A
{1, 2, 3, 4}

It is identical to A | B.

reduce(operator.or_, [A, B]) to join two sets in Python

operator.or_(A, B) returns the bitwiser or of A and B, or union of sets A and B if A and B are sets.

reduce in Python 2.x or functools.reduce in both Python 2.x and 3.x applies function to the items of iterable.

Therefore, reduce(operator.or_, [A, B]) applies or function to A and B. It is the identical to the Python expression A | B

>>> import operator
>>> from functools import reduce
>>> A = {4, 5, 6, 7}
>>> B = {6, 7, 8, 9}
>>> reduce(operator.or_, [A, B])
{4, 5, 6, 7, 8, 9}
Attention

reduce is the built-in function in Python 2.x, but is deprecated in Python 3.

Therefore, we need to use functools.reduce to make the codes compatible in Python 2 and 3.

comments powered by Disqus