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 Compute the Power of a Number
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python Program to Return Multiple Values From a Function
Python range()
Python Program to Catch Multiple Exceptions in One Line
Python Data Structures and Algorithms - Benjamin Baka
Python String endswith()
Python isinstance()
Python Program to Find Numbers Divisible by Another Number
Python Set issubset()
Python Program to Add Two Matrices
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
How to Find an Element in a List with Java
Python Data Types
Python Shallow Copy and Deep Copy
Python Tuple
Python Set discard()
Python iter()
Python sleep()
Converting Between a List and a Set in Java
Python Program to Concatenate Two Lists
Python if...else Statement
Python Set intersection()
Python Object Oriented Programming
Python Program to Create a Long Multiline String
Python Multiple Inheritance
Python Program to Find ASCII Value of Character
Python Program to Swap Two Variables
Python Program to Count the Number of Digits Present In a Number
Python List insert()
Python sorted()
Python Program to Split a List Into Evenly Sized Chunks