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 String encode()
Python Program to Parse a String to a Float or Int
Python String isdecimal()
Python exec()
Python Tuple
Python List append()
Python @property decorator
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Dictionary
Python Program to Iterate Over Dictionaries Using for Loop
Python Program to Get the File Name From the File Path
Python String islower()
Python vars()
Python RegEx
Machine Learning with Python for everyone - Mark E.Fenner
Python Program to Merge Mails
Python filter()
Python Program to Check If a List is Empty
Python oct()
Python Program to Randomly Select an Element From the List
Python Program to Compute the Power of a Number
Python List count()
Python format()
Python Iterators
Python setattr()
Python Program to Extract Extension From the File Name
Python frozenset()
Python Program to Safely Create a Nested Directory
Python Program to Reverse a Number
Python reversed()
Python hash()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho