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 Shuffle Deck of Cards
Python repr()
Python Program to Check the File Size
Python exec()
Python String format_map()
Python Program to Check if a Number is Positive, Negative or 0
Python Dictionary setdefault()
Python List reverse()
Python Program to Check If a String Is a Number (Float)
Python slice()
Python oct()
Python Directory and Files Management
Python Program to Get a Substring of a String
Python sum()
Python id()
Python hex()
Python Program to Add Two Matrices
Python Program to Remove Duplicate Element From a List
Python String isnumeric()
Python Program to Remove Punctuations From a String
Python format()
Python print()
Python String isalnum()
Python dir()
Python Anonymous / Lambda Function
Python Type Conversion and Type Casting
Python Program to Find Sum of Natural Numbers Using Recursion
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python min()
Python Dictionary update()
Python datetime
Python Set difference_update()