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 Program to Trim Whitespace From a String
Python Multiple Inheritance
Python oct()
Python List count()
Python String rfind()
Python Program to Display Powers of 2 Using Anonymous Function
Python bytes()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python Program to Find Armstrong Number in an Interval
Python Program to Copy a File
Python Program to Find Numbers Divisible by Another Number
Python id()
Python Set issuperset()
Python format()
Finding Max/Min of a List or Collection
Python bin()
Python Program to Catch Multiple Exceptions in One Line
Python map()
Python Program to Capitalize the First Character of a String
Python String index()
Python Program to Find the Largest Among Three Numbers
Python List extend()
Python hasattr()
Python Set isdisjoint()
Python Program to Check if a Key is Already Present in a Dictionary
Python enumerate()
How to Get Started With Python?
Python Program to Make a Simple Calculator
Python Objects and Classes
Python String rsplit()
Python Program to Find the Factors of a Number
Python Program to Iterate Through Two Lists in Parallel