Table of Contents
In this tutorial, we will learn about the Python List clear() method with the help of examples.
The clear() method removes all items from the list.
Example
prime_numbers = [2, 3, 5, 7, 9, 11]
# remove all elements
prime_numbers.clear()
# Updated prime_numbers List
print('List after clear():', prime_numbers)
# Output: List after clear(): []
1. Syntax of List clear()
The syntax of clear() method is:
list.clear()
2. clear() Parameters
The clear() method doesn’t take any parameters.
3. Return Value from clear()
The clear() method only empties the given list. It doesn’t return any value.
4. Example 1: Working of clear() method
# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]
# clearing the list
list.clear()
print('List:', list)
Output
List: []
Note: If you are using Python 2 or Python 3.2 and below, you cannot use the clear() method. You can use the del operator instead.
5. Example 2: Emptying the List Using del
# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]
# clearing the list
del list[:]
print('List:', list)
Output
List: []
Visit this page to learn how del operator works in Python.
Related posts:
Python List extend()
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python String rindex()
Python String center()
Python String format_map()
Python Decorators
Python Variables, Constants and Literals
Python map()
Python Program to Add Two Numbers
Ways to Iterate Over a List in Java
Python Set discard()
Python String encode()
Deep Learning with Python - Francois Chollet
Python Custom Exceptions
Java List UnsupportedOperationException
Python Program to Compute the Power of a Number
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Program to Get the Last Element of the List
Python String title()
Python next()
Python zip()
Python Data Structures and Algorithms - Benjamin Baka
Python issubclass()
Python Namespace and Scope
Python Shallow Copy and Deep Copy
Python String format()
Python Program to Remove Punctuations From a String
Python hash()
Python bin()
Python Program to Calculate the Area of a Triangle
Python vars()