Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Lists, Tuples and Ranges

Python list.clear() method

Reference for Python list.clear(): remove every item from a list in place, how it differs from assigning an empty list, and equivalents like del lst[:].

The clear() method removes every item from a list, leaving it empty. It works in place on the same list object and returns None. Added in Python 3.3, it matches dict.clear() and set.clear().

The important detail is that clear() empties the existing object, while items = [] makes the name point at a brand-new list. Other references to the old list see the difference.

Python
items = [1, 2, 3]
items.clear()
print(items)   # []

Try it

Python Emptying a list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python clear() versus rebinding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
list.clear()

This method takes no parameters.

Return value: None.

Raises: nothing. Clearing an empty list is allowed.

Usage notes

  • In place. Every variable that references the list sees it become empty. That is exactly what you want when a function or object shares a list with other code.
  • Rebinding is different. items = [] leaves the old list untouched for anyone else holding it. Pick clear() when the identity of the list matters, and = [] when you simply want a fresh one.
  • Shallow effect. The items themselves are not destroyed, only released. If they are referenced elsewhere they live on. A copy made earlier with copy() is unaffected.
  • Equivalents. del items[:] and items[:] = [] do the same thing and work in code that must also run on very old Pythons. clear() reads best.
  • Returns None. Do not write items = items.clear(), which replaces the list with None.
  • Do not clear while iterating over the same list unless you are leaving the loop immediately.
  • Memory. CPython releases the element storage when a list is cleared, so a cleared list takes very little space.