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()

Argument | Data Type | Explanation |
---|---|---|

`-` | – | – |

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 *. 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.*

**linear runtime complexity**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

**(8th Gen) processor and 16GB of memory. Here’s the code of the experiment:**

*Intel Core i7*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.

`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 as well. . |

`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. |

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 that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a 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.