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 Inheritance
Python locals()
Python super()
Python Program to Find Armstrong Number in an Interval
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Program to Display the multiplication Table
Python Program to Slice Lists
Python List remove()
Removing all Nulls from a List in Java
Python timestamp to datetime and vice-versa
Python max()
Python Program to Get File Creation and Modification Date
Python globals()
Python Program to Count the Number of Digits Present In a Number
Python sorted()
Python Program to Extract Extension From the File Name
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python @property decorator
Python Exception Handling Using try, except and finally statement
Python RegEx
Python Program to Create a Long Multiline String
Python String format()
Python Program to Generate a Random Number
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python Machine Learning - Sebastian Raschka
Python Program to Randomly Select an Element From the List
Python Anonymous / Lambda Function
Python Program to Find the Largest Among Three Numbers
Python Program to Capitalize the First Character of a String
Python String count()
Python List index()
Python Set remove()