Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Set Clear: How to Empty a Set

Learn how to use Python's set.clear() method to remove all elements from a set, understand its behavior and memory impact, and know when to prefer it over reassignment.

~4 min readPython
#Python#Set#Data Structures#Python Methods
A Python set being cleared, with elements fading away and leaving an empty set container, illustrating the set.clear() method.

Python's set.clear() method removes every element from a set in place. It is the standard way to empty a set when you need to keep the same set object alive, such as when other references or data structures point to it. This article covers the syntax, behavior, and practical tradeoffs of using set.clear() in your code.

The Syntax and Basic Behavior

The clear() method is called directly on a set instance. It takes no arguments, returns None, and modifies the set in place. After the call, the set is empty but still exists as the same object.

python
s = {1, 2, 3} s.clear() print(s) # set() print(len(s)) # 0

Because clear() mutates the original object, it does not create a new set. This is different from creating a fresh set with set() or with a set literal such as {1, 2}. The method is available only on mutable sets; frozenset does not have clear() because it is immutable.

What clear() Does to the Original Set Object

The most important detail about clear() is that it preserves the identity of the set. The object you call it on remains the same object, so its identity is unchanged. This matters when other variables, containers, or class attributes reference the same set.

python
s = {1, 2, 3} ref = s s.clear() print(ref) # set() print(s is ref) # True

Both s and ref point to the same set, so clearing through one reference affects the other. If you need to keep the original set intact while creating a new empty set, you should reassign rather than call clear().

clear() vs. Reassigning a New Set

A common alternative to clear() is to assign a new empty set to the variable: s = set(). The two approaches have different consequences for object identity and for any other references that may exist.

python
s = {1, 2, 3} ref = s s = set() # s now points to a new set print(ref) # {1, 2, 3} # the old set is unchanged print(s is ref) # False

Use clear() when you want to empty the set but keep the same object alive, for example when the set is stored in a dictionary or passed to another function that expects the same object. Use reassignment when you no longer need the old set object and want to allow it to be garbage collected, or when you want to avoid mutating a set that other code might still be using.

Memory and Performance Considerations

Calling clear() removes all element references from the set's internal storage. This allows the elements themselves to be garbage collected if no other references exist. The set object remains, and its internal table may be reset to a small default size. Reassigning a new set discards the entire old set object, which can free the memory used by the set's internal table and the set object itself if no other references remain.

For large sets that are reused repeatedly, clear() can be more efficient than repeatedly creating new set objects, because it avoids the overhead of allocating and deallocating a new object each time. However, the exact memory behavior depends on the Python implementation and the garbage collector. There is no universal rule that one is always faster; the choice should be based on whether object identity matters and whether the old set needs to be preserved.

Common Use Cases for clear()

A typical use case is reusing a set as a temporary accumulator in a loop. Instead of creating a new set each iteration, you can clear it at the start of each pass.

python
def unique_words(lines): seen = set() for line in lines: seen.clear() for word in line.split(): seen.add(word) # process seen

Another common scenario is resetting state in a class instance. If a set is an attribute that should be emptied when a reset method is called, clear() ensures that any external references to that attribute still see the empty set.

python
class Session: def __init__(self): self.active_ids = set() def reset(self): self.active_ids.clear()

Edge Cases and Pitfalls

Calling clear() on an empty set is harmless; it simply leaves the set empty. There is no error or special return value.

A more subtle pitfall occurs when you iterate over a set and call clear() inside the loop. Modifying a set during iteration can raise a RuntimeError because the iterator's internal state becomes invalid. The same applies to adding or removing elements during iteration.

python
s = {1, 2, 3} for x in s: s.clear() # RuntimeError: Set changed size during iteration

If you need to empty a set and also process its elements, iterate over a copy of the set and call clear() on the original after the loop.

When Not to Use clear()

Avoid clear() when you need to preserve the original set for other code. If another reference still points to the old set, reassigning the variable leaves that set untouched, which can be safer in code that expects the original data to remain available. Also, if you are working with a frozenset, clear() is not available; you must create a new empty frozenset instead.

Another case is when you want to replace the set with a different type of collection, such as a list or a dictionary. Reassignment is the appropriate approach because clear() only empties the set; it does not change its type.

In performance-sensitive code, the choice between clear() and reassignment may depend on how often the operation occurs and how large the set is. If the set is small and short-lived, reassignment is often simpler and equally efficient. If the set is large and reused frequently, clear() avoids repeated object allocation. Measure your specific workload rather than assuming one approach is always better.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.