Python list.clear() function


The list.clear() method in Python is used to remove all items from a list, effectively emptying it. This method modifies the original list in place and does not return a new list.

Syntax

list.clear()

Return Value

  • The method does not return a value (None is returned implicitly).

Example Usage

  1. Clearing a List:

    my_list = [1, 2, 3, 4, 5] my_list.clear() # Removes all elements from the list print(my_list) # Output: []
  2. Clearing an Already Empty List: Calling clear() on an already empty list does not cause any errors and simply maintains its empty state:

    empty_list = [] empty_list.clear() # Attempting to clear an already empty list print(empty_list) # Output: []
  3. Impact on References: If you have multiple references to the same list object, using clear() will affect all references:

    my_list = [1, 2, 3] another_reference = my_list my_list.clear() # Clears the list print(another_reference) # Output: []
  4. Using clear() with Lists Containing Different Data Types: The clear() method can be used on lists containing various data types:

    mixed_list = [1, 'apple', 3.14, True] mixed_list.clear() # Clears the list print(mixed_list) # Output: []

Summary

  • list.clear() is a simple and efficient way to remove all items from a list in Python.
  • It modifies the original list in place, making it a common choice for resetting lists.
  • The method is safe to use on empty lists, and it impacts all references to the list object, ensuring that all variables pointing to that list reflect its cleared state.