Python List clear()

5/5 - (2 votes)

Surprisingly, even advanced Python coders don’t know about the clear() method of Python lists. Time to change that!

Definition and Usage: The list.clear() method removes all elements from an existing list. The list becomes empty again.

Here’s a short example:

>>> lst = [1, 2, 3, 4, 5]
>>> lst.clear()
>>> lst

In the first line, you create the list lst consisting of five integers. You then remove all elements from the list. The result is the empty list.

Syntax: You can call this method on each list object in Python. Here’s the syntax:


Arguments: The method doesn’t take any argument.

Return value: The method list.clear() has return value None. It operates on an existing list and, therefore, doesn’t return a new list with the removed element


Python List clear()

Related articles:

Here’s your free PDF cheat sheet showing you all Python list methods on one simple page. Click the image to download the high-resolution PDF file, print it, and post it to your office wall:

Python List clear() vs New List

Now, if you’re an alert reader, you may ask the following interesting question: why to use the clear() method in the first place when you also can simply create a new list and be done with it?

Here’s an example where both ways lead to the same result:

>>> lst = [1, 2, 3]
>>> lst.clear()
>>> lst
>>> lst = [1, 2, 3]
>>> lst = []
>>> lst

I know the code seems to be a bit odd but it shows that instead of clearing an existing list, you can also create a new list. In this case, this leads to the exact same result.

However, Python is an object-oriented language. And if you just create a new object and assign it to a variable, the original list still exists in memory. And other variables may point to the object.

Consider the following code snippet that exemplifies this:

lst = [1, 2, 3]
lst_2 = lst
lst = []
# [1, 2, 3]

I’ve created a Python visualization for you so that you can see the objects in memory:

Simply assigning a new list to the variable lst will leave the other variable lst_2 unaffected. Instead, you should have used lst.clear() to make sure that both variables now point to the same empty list object.

lst = [1, 2, 3]
lst_2 = lst
# []

Python List clear() Memory

The effect of the clear() method is that the list is now empty.

In theory, you released the Python virtual machine from the burden of keeping the elements in the memory. Python uses reference counting to determine if some elements in the memory are not referenced anymore (and, thus, can be considered unused). Those elements will be removed—we say, they are deallocated from memory. If you clear the list, you essentially remove all references from the list to the list elements. However, some old list elements may still be referenced from the outside (e.g. by another variable). So they are not necessarily removed because they may still be needed! Just keep this in mind when clearing the list.

In practice, however, even referenced elements may still exist in the memory until the Python garbage collector (or even the operating system) removes the elements from memory.

Python List clear() Complexity

The runtime complexity of list.clear() is O(n) for a list with n elements. Why? Well, you first need to understand what happens if you remove all elements from a list. The list elements are not physically (or, for that matter, digitally) stored in the list. The list contains only references to the real list element objects in memory. If you clear the list, you remove all those references.

The garbage collector in Python goes over all elements in the memory to remove the ones that have a reference count of zero. Why? Because they are the ones that cannot be accessed in the code. Thus, the garbage collector can safely assume that they are unused and are not needed anymore. As you see, the garbage collector needs the reference count information for each element in memory.

The algorithm when clearing a list is simple: reduce the reference count of each list element object by one. The objects that end up with reference count zero can now be removed from memory. But as you need to go over all list elements, the runtime complexity is linear to the list size.

Python List clear() Not Working

The Python list.clear() method was added in Python 3.3 (official source). So if you try to use it for any Python version before that, you must use the del list[:] method that is semantically equivalent and works for earlier Python versions, too.

Related articles on the Finxter blog:

Python List clear() Version 2.7

Have you tried to use Python list.clear() in Python 2.7? It’s not possible. The clear() method was added in Python 3.3 (official source). So if you try to use it for any Python version before that (including 2.7), you must use the del list[:] method that is semantically equivalent and works for earlier Python versions, too.

Related articles on the Finxter blog:

Python List clear() vs del

You may ask: what’s the difference between the list.clear() method and the del operation?

The answer is simple: there isn’t any semantic difference. The list.clear() method is just syntactical sugar for del list[:] (source).

Here’s an example demonstrating that both are, in fact, the same:

>>> lst = [1, 2, 3]
>>> lst.clear()
>>> lst
>>> lst = [1, 2, 3]
>>> del lst[:]
>>> lst

List Removal Alternatives

There are some alternative list methods to remove elements from the list. See the overview table:

lst.remove(x)Remove an element from the list (by value)
lst.pop()Remove an element from the list (by index) and return the element
lst.clear()Remove all elements from the list
del lst[3]Remove one or more elements from the list (by index or slice)
List comprehensionRemove all elements that meet a certain condition

Python List clear() Thread Safe

Do you have a multiple threads that access your list at the same time? Then you need to be sure that the list operations (such as clear()) are actually thread safe.

In other words: can you call the clear() operation in two threads on the same list at the same time? (And can you be sure that the result is meaningful?)

The answer is yes (if you use the cPython implementation). The reason is Python’s global interpreter lock that ensures that a thread that’s currently working on it’s code will first finish its current basic Python operation as defined by the cPython implementation. Only if it terminates with this operation will the next thread be able to access the computational resource. This is ensured with a sophisticated locking scheme by the cPython implementation.

The only thing you need to know is that each basic operation in the cPython implementation is atomic. It’s executed wholly and at once before any other thread has the chance to run on the same virtual engine. Therefore, there are no race conditions. An example for such a race condition would be the following: the first thread reads a value from the list, the second threads overwrites the value, and the first thread overwrites the value again invalidating the second thread’s operation.

All cPython operations are thread-safe. But if you combine those operations into higher-level functions, those are not generally thread safe as they consist of many (possibly interleaving) operations.

Python List Clear Duplicates

How to remove all duplicates of a given value in the list?

The naive approach is to go over each element and check whether this element already exists in the list. If so, remove it. However, this takes a few lines of code.

A shorter and more concise way is to create a dictionary out of the elements in the list. Each list element becomes a new key to the dictionary. All elements that occur multiple times will be assigned to the same key. The dictionary contains only unique keys—there cannot be multiple equal keys.

As dictionary values, you simply take dummy values (per default).

Related blog articles:

Then, you simply convert the dictionary back to a list throwing away the dummy values. As the dictionary keys stay in the same order, you don’t lose the order information of the original list elements.

Here’s the code:

>>> lst = [1, 1, 1, 3, 2, 5, 5, 2]
>>> dic = dict.fromkeys(lst)
>>> dic
{1: None, 3: None, 2: None, 5: None}
>>> duplicate_free = list(dic)
>>> duplicate_free
[1, 3, 2, 5]

Where to Go From Here?

The list.clear() method removes all elements from the list.

You’ve learned the ins and outs of this important Python list method.

If you keep struggling with those basic Python commands and you feel stuck in your learning progress, I’ve got something for you: Python One-Liners (Amazon Link).

In the book, I’ll give you a thorough overview of critical computer science topics such as machine learning, regular expression, data science, NumPy, and Python basics—all in a single line of Python code!

Get the book from Amazon!

OFFICIAL BOOK DESCRIPTION: Python One-Liners will show readers how to perform useful tasks with one line of Python code. Following a brief Python refresher, the book covers essential advanced topics like slicing, list comprehension, broadcasting, lambda functions, algorithms, regular expressions, neural networks, logistic regression and more. Each of the 50 book sections introduces a problem to solve, walks the reader through the skills necessary to solve that problem, then provides a concise one-liner Python solution with a detailed explanation.