Python List clear() Method

Removes all items from the list

Usage

Use clear() method to remove all items from the list.

The method does not return anything; it modifies the list in place.

Syntax

list.clear()

Basic Example

Example: Clear the list

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

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.

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

Example:

L = ['red', 'green', 'blue']
del L[:]
print(L)    # []

Assigning empty list to a start-to-end slice will have same effect as clear().

Example:

L = ['red', 'green', 'blue']
L[:] = []
print(L)    # []

Multiplying 0 to a list using multiplication assignment operator will remove all items from the list in place.

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

Example:

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