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 Comprehension
Python Inheritance
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python Object Oriented Programming
Python String casefold()
Python String lstrip()
Java – Get Random Item/Element From a List
Python String join()
Python exec()
Python Deep Learning Cookbook - Indra den Bakker
Python Set add()
Python Set discard()
Python Program to Make a Flattened List from Nested List
Python Objects and Classes
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Set issubset()
Python Program to Multiply Two Matrices
Python Program to Sort a Dictionary by Value
How to Convert List to Map in Java
Python Multiple Inheritance
Python Program to Count the Occurrence of an Item in a List
Python complex()
Python Program to Find the Factors of a Number
Python Program to Append to a File
Python round()
Python Modules
Python int()
Python Program to Create Pyramid Patterns
Python Program to Convert Celsius To Fahrenheit
Python strptime()
Python Program to Find Factorial of Number Using Recursion
Python Set difference_update()