Python

How to clear all elements from List in Python

The Python clear() method is used to clear all elements from the list.

How to clear elements from List in Python:

the clear() method can be applied on a python list to remove all elements, it doesn’t take any values as parameters and doesn’t return (None) anything.

1. list.clear()

In the following example, I am going to create a list first and remove all elements at a once.

if __name__ == '__main__':
    fruits = ['Apple','Banana','Gua','Pineapple','Mango']
    # Before clearing the list
    print(fruits)
    fruits.clear()
    # After clearing the list
    print(fruits)

Output:

['Apple', 'Banana', 'Gua', 'Pineapple', 'Mango']
[]

2. del:

del is a keyword in python, which is used to delete objects, lists or part of lists

if __name__ == '__main__':
    fruits = ['Apple','Banana','Gua','Pineapple','Mango']
    # Before clearing the list
    print(fruits)
    del fruits[:]
    # After clearing the list
    print(fruits)

Output:

['Apple', 'Banana', 'Gua', 'Pineapple', 'Mango']
[]

3. *=0

A python list can be empty by multiplying with 0 like below.

if __name__ == '__main__':
    fruits = ['Apple','Banana','Gua','Pineapple','Mango']
    # Before clearing the list
    print(fruits)

    # After clearing the list

    fruits *=0
    # After clearing the list
    print(fruits)

Output:

['Apple', 'Banana', 'Gua', 'Pineapple', 'Mango']
[]

Reference:

Happy Learning :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

Python

Python Dictionary Methods and Usages

Hi everyone, In this tutorial, we will learn about Python dictionary usages and its methods using examples. 1. What is a Python Dictionary? Dictionary in Python is a…

Ask a question or leave a comment