Python Set clear()

Rate this post

Python’s `set.clear()` method removes all elements from this set. All variables that refer to this set object will refer to an empty set after calling the method.

Here’s a minimal example where you remove three elements from a set at once by means of the `s.clear()` method:

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

Syntax

Let’s “dive” into the formal syntax of the `set.clear()` method—a simple exercise! 🙂

`set.clear()`

The `set.clear()` function takes no arguments, not even an optional one. If you try to pass an argument into the `set.clear()` function, it’ll throw a `TypeError: clear() takes no arguments (1 given)`.

```>>> s = {1, 2, 3}
>>> s.clear(2)
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
s.clear(2)
TypeError: clear() takes no arguments (1 given)```

Return Value of Set clear()

The return value of `set.clear()` is `None`.

The Aliasing Problem with Set clear()

You may run into the problem where two variables `var_1` and `var_2` point to the same set. If you clear the set on one variable, e.g., `var_1.clear()`, you’ll see the effect on the second variable, e.g., `var_2`, that also becomes empty. Keep this in mind!

```>>> var_1 = {'Alice', 'Bob', 'Liz'}
>>> var_2 = var_1
>>> var_1.clear()
>>> var_1
set()
>>> var_2
set()```

Both variable now refer to an empty object because the `clear()` function really works on the set object, not the variable pointing to it—and it doesn’t create a copy first so be careful!

What is the Time Complexity of Set clear()?

The runtime complexity of the `set.clear()` function on a set with n elements is O(n). So, Python’s `set.clear()` method has linear runtime complexity. The reason is that it iterates over all elements in the set and removes them one-by-one—the more elements there are, the longer it takes.

You can see this in the following simple experiment where we run the set method multiple times for an increasing number of set elements.

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 = [10**3, 10**4, 10**5, 10**6, 10**7, 10**8]
runtimes = []

for size in sizes:
s = set(range(size))

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

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.