Python Set update()

Rate this post

Python’s set.update(set_1, set_2, ...) performs the union of all involved sets and updates the set on which it is called. It adds all members of the set argument(s) to the set on which it is called. For example, s.update({1, 2}) adds elements 1 and 2 to the original set s.

Python Set update() - Examples, Explanation, Runtime

Here’s a minimal example that creates the union of two sets s and t and updates set s accordingly:

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

Syntax

Let’s dive into the formal syntax of the set.update() method.

set.update(*sets)
ArgumentData TypeExplanation
*setsOne or more setsThe elements of those sets will be unionized

Return Value of Set update()

The return value of set.update() is None. But the method has side-effects. It adds all elements of the set argument or arguments to the set on which it is called.

Advanced Examples Set Update

There are some subtleties you need to understand regarding the set update method. Let’s dive into them by example!

The straightforward example is to calculate the update of a superset with one of its subsets. In this case, the result is the superset set because all elements in the subset are already elements of the superset, by definition of the set union.

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

But what if you’d invert this and calculate the union of a subset and a superset? In this case, the result is the same as before:

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

Can you compute the union of a set and an empty set? Sure! The return value is the larger set.

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

Set Update Multiple Set Arguments

You can compute the union of an original set and an arbitrary number of set arguments. In this case, the set on which it is called will contain the elements that are members of any of the involved sets.

Here’s an example:

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

All elements are members of the original set s.

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!

Python Set Update vs Add

Both set.update() and set.add() modify the existing set on which the method is called. However, set.update() adds all elements in an iterable such as a set, whereas set.add() only adds a single element.

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.

Here’s an example of the set.add() method:

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

The original set s is modified and now contains four elements after adding a single element 4.

What is the Time Complexity of Set Update in Python?

The runtime complexity of the set.update() method is the same as the runtime complexity of the union operator. If your set argument has m elements, the complexity is O(m) because you need to insert all m elements into the original set.

You can see this in the following simple experiment where we run the set method multiple times for increasing set sizes:

What is the Time Complexity of Set Update in Python?
Figure: The runtime increases approximately linearly with increasing set sizes.

I ran this experiment on my Acer Aspire 5 notebook (I know) with Intel Core i7 (8th Gen) processor and 16GB of memory. Here’s the code of the experiment:

import matplotlib.pyplot as plt
import time

sizes = [i * 10**5 for i in range(50)]
runtimes = []

for size in sizes:
    s = set(range(1, size, 2))
    t = set(range(0, size, 2))

    # Start track time ...
    t1 = time.time()
    s.update(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()

Python Set Update List

You can update an existing set with all elements in a given list by calling set.update(list). This will insert all elements from the list in the set. As the set data structure is duplicate-free, all duplicate entries will be removed.

Here’s an example where you pass a list as an argument. Python will simply iterate over all elements in the list and add them to the existing set:

>>> s = {1, 2, 3}
>>> s.update(['Alice', 'Bob'])
>>> s
{1, 2, 3, 'Alice', 'Bob'}

Other Python Set Methods

All set methods are called on a given set. For example, if you created a set s = {1, 2, 3}, you’d call s.clear() to remove all elements of the set. We use the term “this set” to refer to the set on which the method is executed.

add()Add an element to this set
clear()Remove all elements from this set
copy()Create and return a flat copy of this set
difference()Create and return a new set containing all elements of this set except the ones in the given set arguments. The resulting set has at most as many elements as any other.
difference_update()Remove all elements from this set that are members of any of the given set arguments.
discard()Remove an element from this set if it is a member, otherwise do nothing.
intersection()Create and return a new set that contains all elements that are members of all sets: this and the specified set(s).
intersection_update()Removes all elements from this set that are not members in all other specified sets.
isdisjoint()Return True if no element from this set is a member of any other specified set. Sets are disjoint if and only if their intersection is the empty set.
issubset()Return True if all elements of this set are members of the specified set argument.
issuperset()Return True if all elements of the specified set argument are members of this set.
pop()Remove and return a random element from this set. If the set is empty, it’ll raise a KeyError.
remove()Remove and return a specific element from this set as defined in the argument. If the set doesn’t contain the element, it’ll raise a KeyError.
symmetric_difference()Return a new set with elements in either this set or the specified set argument, but not elements that are members of both.
symmetric_difference_update()Replace this set with the symmetric difference, i.e., elements in either this set or the specified set argument, but not elements that are members of both.
union()Create and return a new set with all elements that are in this set, or in any of the specified set arguments.
update()Update this set with all elements that are in this set, or in any of the specified set arguments. The resulting set has at least as many elements as any other.