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 Namespace and Scope
Python Program to Display the multiplication Table
Python Program to Check the File Size
Python Program to Randomly Select an Element From the List
Python Dictionary get()
Python dir()
Python repr()
Python Directory and Files Management
Python Program to Calculate the Area of a Triangle
Python Program to Check Whether a String is Palindrome or Not
Python Set update()
Python time Module
Python Program to Append to a File
Removing all Nulls from a List in Java
Python Program to Find LCM
Python String rindex()
Python Program to Print Output Without a Newline
Python divmod()
Python all()
Python Statement, Indentation and Comments
Python Program to Merge Two Dictionaries
Python Exception Handling Using try, except and finally statement
Python String swapcase()
Python eval()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python List copy()
Python Program to Represent enum
Python Objects and Classes
Python help()
Python Set intersection_update()
Python Program to Sort Words in Alphabetic Order
Python Set issubset()