w3resource

Python List: clear() Method

clear() Method

The clear() method is used to remove all items from a given list.

Visual Explanation:

Python List: clear() method

Syntax:

list.clear()

Parameter: No parameters

Equivalent Command of clear() method:

del a[:]

Example: clear() method


# colors list
colors = ['Red', 'Green', 'Black']
print("Original list:") 
print(colors) 
print("Clearing the said list:")
colors.clear()
print("New list:",colors)

Output:

Original list:
['Red', 'Green', 'Black']
Clearing the said list:
New list: []

Example: Remove miscellaneous items from a list


# colors list
nums = ["Red",('d'), {1, 2, 3}, [10.10, 45.2, 500]]
print("Original list:") 
print(nums) 
print("Clearing the said list :")
nums.clear()
print("New list:",nums)

Output:

Original list:
['Red', 'd', {1, 2, 3}, [10.1, 45.2, 500]]
Clearing the said list :
New list: []

Clearing list items without clear() method

Example: Clearing list using del statement


# colors list
colors = ['Red', 'Green', 'Black']
print("Original list:") 
print(colors) 
print("Clearing the said list using del statement:")
del colors[:]
print("New list:",colors)

Output:

Original list:
['Red', 'Green', 'Black']
Clearing the said list using del statement:
New list: []

Example: Clearing list using "*= 0"


# colors list
colors = ['Red', 'Green', 'Black']
print("Original list:") 
print(colors) 
print("Clearing the said list using *= 0:")
colors *= 0
print("New list:",colors)

Output:

Original list:
['Red', 'Green', 'Black']
Clearing the said list using *= 0:
New list: []

Example: Clearing list

This method doesn't affect other references:


>>> colors = ['Red', 'Green', 'Black']
>>> temp = colors
>>> colors = []
>>> print(colors)
[]
>>> print(temp)
['Red', 'Green', 'Black']

Python Code Editor:

Previous: Python List append() Method
Next: Python List copy() Method

Test your Python skills with w3resource's quiz



Follow us on Facebook and Twitter for latest update.