What is the list.clear() method in Python?
In Python, the list.clear() method is used to remove all items of a list.
Syntax
list.clear()
Parameters
list.clear() does not accept any parameters.
Return value
list.clear() does not return a value.
Code
Let’s use the list.clear() method to remove all the items of a list of even numbers up to ten.
# let us create a list of even numbers up to teneven_numbers = [2, 4, 6, 8, 10]# let us remove all items of the listeven_numbers.clear()print(even_numbers)
Explanation
- In line 2: We created a list called
even_numbers. - In line 4: We introduced the
list.clear()method to remove all items of the list. - In line 5: We printed the modified list.
Let’s create another list of some countries and then use the list.clear() method to remove all the items of the list.
countries = ['USA', 'GHANA', 'ITALY', 'ARGENTINA', 'CHINA', 'AUSTRALIA']# let us remove all the items of the listcountries.clear()print(countries)