Python List clear()

Python List clear() is a built-in function that removes all the items and makes a list empty.

In this tutorial, we will learn about the Python list clear() method with the help of examples.

Syntax of List clear() 

The syntax of the clear() method is:

list.clear()

clear() Parameters

The clear() method does not take any parameters.

Return Value from List clear()

The clear() method empties the given list but does not return any value.

Example 1: Working of clear() method

# list of cars
cars = ['Benz',('volkswagen','BMW'),'Ford','Ferrari',('volkswagen','BMW')]
numbers= [1,(1,3),5,7,(1,3),3,1,6,(1,3)]

# clear the car list
cars.clear()
print("After clearing the car list = ",cars)

# clear the number list
numbers.clear()
print("After clearing the number list = ",numbers)

Output

After clearing the car list =  []
After clearing the number list =  []

Note: If you are using the Python 2 or Python 3.2 you cannot use the clear() method as it is not present. Instead you can use del operator to empty the list.

Example 2: Emptying the List Using del

# list of cars
cars = ['Benz',('volkswagen','BMW'),'Ford','Ferrari',('volkswagen','BMW')]
numbers= [1,(1,3),5,7,(1,3),3,1,6,(1,3)]

# deletes all the elements in the car list
del cars[:]
print("After clearing the car list = ",cars)

# deletes all the elements in the number list
del numbers[:]
print("After clearing the number list = ",numbers)

Output

After clearing the car list =  []
After clearing the number list =  []
Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
Python List Extend()

Python List extend()

Table of Contents Hide Syntax of List extend() extend() ParametersReturn Value from List extend()Difference between append() and extend() method in PythonExample 1: How to use List extend() MethodExample 2: Add Elements…
View Post
Graphviz'S Executables Not Found

Graphviz’s executables not found

Table of Contents Hide How to Fix InvocationException: graphviz’s executables not found?On WindowsOn LinuxOn macOS Graphviz is open source graph visualization software that helps represent structural information as diagrams of…
View Post
Python String Index()

Python String index()

Table of Contents Hide index() Syntaxindex() Parametersindex() Return ValueDifference between index() method and find() methodExample 1: Find the index of a string in PythonExample 2: If string is not found…
View Post