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:
How to Convert List to Map in Java
Ways to Iterate Over a List in Java
Python String lower()
Python String isalpha()
Python Program to Get Line Count of a File
Python super()
Python Program to Print Colored Text to the Terminal
Converting Between a List and a Set in Java
Converting between an Array and a List in Java
Python Program to Merge Mails
Convert a Map to an Array, List or Set in Java
Python Program to Convert Decimal to Binary Using Recursion
Python String endswith()
Python Shallow Copy and Deep Copy
Python String format()
Python String casefold()
Python all()
Python Program to Find HCF or GCD
Python Program to Create a Long Multiline String
Python Machine Learning Eqution Reference - Sebastian Raschka
Python Program Read a File Line by Line Into a List
Python Program to Append to a File
Python Program to Print the Fibonacci sequence
Python Set symmetric_difference()
Python issubclass()
Python Program to Check if a Key is Already Present in a Dictionary
Python Program to Check Whether a String is Palindrome or Not
Python Program to Calculate the Area of a Triangle
Python Machine Learning - Sebastian Raschka
Python Functions
Remove the First Element from a List
Python Program to Display Powers of 2 Using Anonymous Function