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

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like
Python Dictionary Get()

Python Dictionary get()

Table of Contents Hide Syntax of Dictionary get() get() ParametersReturn Value from Dictionary get()Example 1 – How to use get() method in DictionaryExample 2 – Difference between get() method and dict[key]…
View Post
Check If List Is Empty Python

Check if list is empty in Python

Table of Contents Hide  How to Check if List is Empty in PythonSolution 1: Using PEP 8 recommended Style.Solution 2: Using the bool() methodSolution 3: Using the len() method.Solution 4:…
View Post