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:
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Program to Return Multiple Values From a Function
Python type()
Python Program to Convert Two Lists Into a Dictionary
Python Function Arguments
Python String isalnum()
Python Program to Find the Factorial of a Number
Python Program to Count the Number of Each Vowel
Python Program to Add Two Matrices
Python String split()
Python Program to Make a Flattened List from Nested List
Python Program to Add Two Numbers
Python timestamp to datetime and vice-versa
Python String encode()
Python Dictionary keys()
Python Tuple
Python sleep()
Python String center()
Python filter()
Python memoryview()
Python locals()
Python Multiple Inheritance
Python ascii()
Python Global Keyword
Python String title()
Python String rjust()
Python Program to Concatenate Two Lists
Python String isdecimal()
Python String isnumeric()
Python Program to Find HCF or GCD
Python str()
Python Program to Find All File with .txt Extension Present Inside a Directory