89DEVs

Python List clear()

Python List clear()

How to remove all elements from a list? The clear() method of Python Lists removes all items from the list. After the clear() method is called, the list is empty and can be filled again.

Clear a list

To clear a list in Python, use the clear() method as shown below. # clear a list in python numbers = [1, 2, 3] numbers.clear() print(numbers) In this example, a list of numbers contains the integer values 1, 2 and 3. Then, the clear() method is called on the list. Finally, the cleared list is printed and as shown below the list is now empty. []

del operator

The clear() method has the same effect as the del operator applied to the range of the list. # clear a list using the del operator numbers = [1, 2, 3] del numbers[:] print(numbers) In this example, the same list of numbers as above is defined. It contains the integer values 1, 2 and 3. Then, the del operator is applied to the range of the list using the slice notation [:]. Finally, the cleared list is printed and the result is the same as above where we used the clear() method. [] In case the del operator is used without slice notations the list is deleted, instead of emptied. # delete list using the del operator numbers = [1, 2, 3] del numbers print(numbers) Here, the same list of number is defined. It contains the integer values 1, 2 and 3. Then, the del operator is applied on the list, not using slice notation. This deletes the whole list instead of the elements within the list. The list doesn't exist anymore and a NameError exception is raised during the print statement. NameError: name 'numbers' is not defined

Syntax of List clear()

The syntax of the clear() method is: list.clear()

Arguments of List clear()

The clear() method doesn't accept any arguments. If an argument is passed, a TypeError exception is raised. TypeError: list.clear() takes no arguments (1 given)

Return value of List clear()

The clear() method doesn't return any value. It just removes all elements from a list and this results in an empty list.

                
        

Summary


Click to jump to section