Python List clear() Method (with Examples)

Python List clear() Method: In this tutorial, we will learn about the clear() method of the list class with its usage, syntax, parameters, return type, and examples. By IncludeHelp Last updated : June 20, 2023

Python List clear() Method

The clear() is an inbuilt method of the list class that is used to clear a list i.e. it is used to remove all elements from the list. The method is called with this list and returns nothing.

Syntax

The following is the syntax of clear() method:

list_name.clear()

Parameter(s):

The following are the parameter(s):

  • None - It does not accept any parameter.

Return Value

The return type of this method is <class 'NoneType'>, it returns nothing.

Example 1: Use of List clear() Method

# declaring a list
cities = ["New Delhi", "Mumbai", "Banglore"]

# printing elements before clearing the list
print("Before clear() method...")
print("cities = ", cities)

# clearing the list
cities.clear()

# printing elements after clearing the list
print("After clear() method...")
print("cities = ", cities)

Output

Before clear() method...
cities =  ['New Delhi', 'Mumbai', 'Banglore']
After clear() method...
cities =  []

Example 2: Use of List clear() Method

# declaring the lists
x = ["ABC", "XYZ", "PQR"]
y = ["PQR", "MNO", "YXZ"]
z = ["123", "456", "789"]

# printing sets before clearing the list
print("Before clear() method...")
print("x: ", x)
print("y: ", y)
print("z: ", z)

# clearing the lists
x.clear()
y.clear()
z.clear()

# printing sets after clearing the list
print("After clear() method...")
print("x: ", x)
print("y: ", y)
print("z: ", z)

Output

Before clear() method...
x:  ['ABC', 'XYZ', 'PQR']
y:  ['PQR', 'MNO', 'YXZ']
z:  ['123', '456', '789']
After clear() method...
x:  []
y:  []
z:  []

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.