clear() in Python | clear() Method in Python
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
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:
Output:
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.
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:
Output:
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
Output:
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.