clear() in Python | clear() Method in Python

quiz
Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Overview

The clear() function in Python removes all elements from a list. The function does not take any parameters and does not return anything.

Syntax of clear() function in Python

list.clear()

Parameters of clear() function in Python

The clear method in Python doesn’t take any parameters.

Return Type of clear() function in Python

The clear() function simply clears the given list. It does not return any particular value.

Example of clear() function in Python

Code:

# declaring a list
my_list = [{1, 2}, ('xyz'), ['3.66', '2.2']]

# clearing the list
my_list.clear()

print('The list after using the clear function:', my_list)

Output:

The list after using the clear function: []

What is clear() List method in Python?

The clear() method clears a list of all its entries. It removes everything from the list and returns an empty list. It doesn't take any parameters and doesn't throw an exception if the list is empty.

What is clear list in Python

Note:

The clear() function is part of the standard library and entirely clears the Python list.

More Examples

Example 1: Emptying the list using del() method as an alternative of clear() method

Code:

# declaring a list
my_list = [{1, 2}, ('xyz'), ['3.66', '2.2']]

# clearing the list
del my_list[:]

print('The list after using del:', my_list)

Output:

The list after using del: []

Explanation:

In the above example code snippet, we have made use of del to clear a list in Python. First, we have declared a list. Next, we have used del and then printed the list to see its contents. Similar to clear, del also empties the list.

Example 2: Using the clear() method if the list is already empty

# creating a list that is already empty 
my_list = []  

# iterating the list
for i in my_list:  
    print(i)  
    
my_list.clear()  
print("After clearing the list:") 

# iterating the list 
for i in my_list:   
    print(i)  

Output:

After clearing the list:

Explanation:

Here, we have taken an example of a list that is already empty. On iterating the list after using the clear function, we can see that no elements are stored in the list.

Conclusion

  • The clear() method of the standard library is used while working with lists and dictionaries.
  • It does not take any inputs or parameters.
  • The function does not return anything but clears the list's contents or dictionary.

See Also

Free Courses by top Scaler instructors