PythonLists and tuples
list. clear()
Removes all the items from a list.
- Returns
None- Changes the original
- Yes
Example
#Python
cart = ["HTML course", "Python course"]
same_cart = cart
cart.clear()
print(cart, same_cart)
cart = ["CSS course"]
print(cart, same_cart)Resultsaved result, you can check it
[] []
['CSS course'] []
Definition and usage
#The clear() method empties the list in place. After calling it, the list has a length of 0, but it is still the same object.
This matters when several variables point to the same list. clear() empties it for all of them, while the assignment my_list = [] only replaces the list in one variable.
The equivalent statement is del my_list[:].
Syntax
#Syntax
list.clear()Good practices
#- When other parts of the program hold a reference to the list, use
clear()so everyone sees an empty list. - Checking for emptiness:
if not my_list:.
Related entries
#Spotted a mistake or missing an example? Write to us.