Skip to content

Python clear list | Remove all items in Python list

  • by

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

list.clear()

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 a simple example of it.

oldlist = ["a", "b", "c", "d"]
newList = oldlist.clear()
print(newList)

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

list1 = ["a", "b", "c", "d"]

list1.clear()  # Python 3.3+, most obvious
print(list1)

list2 = [1, 2, 3, 4]
del list2[:]
print(list2)

list3 = [1, 2, 3, 4]
list3[:] = []
print(list3)

list4 = ["a", "b", "c", "d"]
list4 *= 0  # fastest
print(list1)

Output:

Python clear list

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

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

emptyList = []
newList = emptyList.clear()
print(newList)

Output: None

Q: How to remove a single item from the Python list?

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

list1 = [3, 4, 1, 1, 8, 9]
list1.remove(4)
print(list1)

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading