Join Two Sets in Python

Jinku Hu Jan 30, 2023 Dec 01, 2019
  1. A |= B to Join Two Sets in Python
  2. A.update(B) to Join Two Sets in Python
  3. A.union(B) to Join Two Sets in Python
  4. reduce(operator.or_, [A, B]) to Join Two Sets in Python
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.

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

Related Article - Python Set