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



Share this Tutorial / Exercise on : Facebook and Twitter

Python: Tips of the Day

Inserting if statements using conditional list comprehensions:

x = [1, 2, 3, 4, 5, 6]
result = []
for idx in range(len(x)):
    if x[idx] % 2 == 0:
        result.append(x[idx] * 2)
    else:
        result.append(x[idx])
result

Output:

[1, 4, 3, 8, 5, 12]
[(element * 2 if element % 2 == 0 else element) for element in x]

Output:

[1, 4, 3, 8, 5, 12]
[element * 2 for element in x if element % 2 == 0]

Output:

[4, 8, 12]