>>> s = {1, 2, 3, 4} >>> t = {3, 4, 5} >>> s.union(t) {1, 2, 3, 4, 5}

Table of Contents

## Syntax

set.union(*sets)

## Return Value of Set union()

## Advanced Examples Set Union

>>> {1, 2, 3}.union({1, 2}) {1, 2, 3}

>>> {1, 2}.union({1, 2, 3}) {1, 2, 3}

>>> {1, 2, 3}.union(set()) {1, 2, 3}

## Set Union Multiple Set Arguments

>>> {1, 2, 3, 4, 5, 6}.union({0, 2}, {42, 3, 4}, {33, 3, 5}) {0, 1, 2, 3, 4, 5, 6, 33, 42}

## Python Set Union | Operator

>>> {1, 2}.union({3, 4}) {1, 2, 3, 4} >>> {1, 2} | {3, 4} {1, 2, 3, 4}

>>> {1, 2} | {3, 4} | {5, 6} {1, 2, 3, 4, 5, 6}

## Python Set Update vs Union

Both `set.update()`

and `set.union()`

perform the union operation. However, `set.update()`

adds all missing elements to the set on which it is called whereas `set.union()`

creates a new set. Consequently, the return value of `set.update()`

is `None`

(with side effects) and the return value of `set.union()`

is a set (without side effects).

Here’s an example of the `set.update()`

method:

>>> s = {1, 2, 3} >>> s.update({4, 5}) >>> s {1, 2, 3, 4, 5}

The original set `s`

is modified and now contains five elements after the update. There is no return value, so you need to separately print out the set.

Here’s an example of the `set.union()`

method:

>>> s = {1, 2, 3} >>> s.union({4, 5}) {1, 2, 3, 4, 5}

Both sets remain unchanged. However, a new set has been created—and this set is the return value of the operation!

## What is the Time Complexity of Set Union in Python?

import matplotlib.pyplot as plt import time sizes = [i * 10**5 for i in range(50)] runtimes = [] for size in sizes: s = set(range(size)) t = set(range(0, size, 2)) # Start track time ... t1 = time.time() s.union(t) t2 = time.time() # ... end track time runtimes.append(t2-t1) plt.plot(sizes, runtimes) plt.ylabel('Runtime (s)') plt.xlabel('Set Size') plt.show()

## Other Python Set Methods

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.