Python List clear() Method

Removes all items from the list

Usage

Use clear() method to remove all items from the list. This method does not return anything; it modifies the list in place.

Syntax

list.clear()

Basic Example

L = ['red', 'green', 'blue']
L.clear()
print(L)
# Prints []

Please note that clear() is not same as assigning an empty list L = [].

L = [] does not empty the list in place, it overwrites the variable L with a different list which happens to be empty.

If anyone else had a reference to the original list, that remains as is; which may create a problem.

Equivalent Methods

For Python 2.x or below Python 3.2 users, clear() method is not available. You can use below equivalent methods.

  1. You can remove all items from the list by using del keyword on a start-to-end slice.

    L = ['red', 'green', 'blue']
    del L[:]
    print(L)
    # Prints []
  2. Assigning empty list to a start-to-end slice will have same effect as clear().

    L = ['red', 'green', 'blue']
    L[:] = []
    print(L)
    # Prints []
  3. Multiplying 0 to a list using multiplication assignment operator will remove all items from the list in place.

    L = ['red', 'green', 'blue']
    L *= 0
    print(L)
    # Prints []

    Any given integer that is less than or equal to 0 would have the same effect.