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 Convert String to Datetime
Python Program to Differentiate Between type() and isinstance()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python Program to Get the Class Name of an Instance
Python RegEx
Python Program to Count the Occurrence of an Item in a List
Python set()
Python String isdecimal()
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Program to Print all Prime Numbers in an Interval
Python String rstrip()
Python String splitlines()
Python String replace()
Python Program to Find the Largest Among Three Numbers
Python String capitalize()
Finding Max/Min of a List or Collection
Python Program to Transpose a Matrix
Python Program to Find the Factors of a Number
Python oct()
APIs in Node.js vs Python - A Comparison
Python Program to Convert Celsius To Fahrenheit
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python Set issuperset()
Deep Learning with Python - Francois Chollet
Python max()
Python int()
Python Program to Count the Number of Each Vowel
Python List sort()
Python String maketrans()
Python Program to Make a Flattened List from Nested List
Python List remove()
Python Dictionary clear()