Python clear list | Remove all items in Python list

You can clear a Python list by using the clear() function. Python clear() function removes all items from the list. There are many ways to do delete or remove all items from the Python list.

Syntax

Example of Python clear list

The clear() method doesn’t take any parameters and doesn’t return any value. It’s only emptying the given list.

See below simple example of it.

Output: None

Other ways

To actually clear a list in-place, you can use any of these ways:

  1. alist.clear() # Python 3.3+, most obvious
  2. del alist[:]
  3. alist[:] = []
  4. alist *= 0 # fastest

Example

Output:

Python clear list

Q: Will clear() method work on empty list?

Answer: Nothing will happens, If you try a delete elements of empty list using clear() method. Even there is no error.

Output: None

Q: How to remove single item from Python list?

Answer: You have to use e “Python list remove() function” to remove elements (items) form the list. 

Output: [3, 1, 1, 8, 9]

Must Read:- Python list remove() function

Do comment if you have any doubts and suggestions on this topic.

Note: This example (Project) is developed in PyCharm 2020.1 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.15.4
Python 3.7
All Python Programs code is in Python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.