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:
Deep Learning with Python - Francois Cholletf
Python Shallow Copy and Deep Copy
Python eval()
Python Set add()
Python Machine Learning - Sebastian Raschka
Python ascii()
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python List sort()
Python String find()
Python Program to Get the Class Name of an Instance
Python compile()
Python Variables, Constants and Literals
Python list()
Python Objects and Classes
Python Program to Shuffle Deck of Cards
Python Program to Find the Largest Among Three Numbers
Python Program to Check If a List is Empty
Python any()
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python List index()
Python Set issubset()
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python Program to Add Two Matrices
Python staticmethod()
Python oct()
Python format()
Python Program to Represent enum
Python strftime()
Python bytearray()
Python Program to Trim Whitespace From a String
Python id()
APIs in Node.js vs Python - A Comparison