Python Remove all, Clear
Use .clear() method to remove all elements in sequence.
Syntax:variable.clear()Return Value:
no return valueUse
- Remove - to remove element by value.
- Pop - to remove element by index.
- Clear - to remove all elements.
List Remove all, Clear
Alternative option is to assign empty list.
# Example, List Remove all, Clear
a1 = [10, 20, 30, 40, 50, 20]
a1.clear()
print(a1) # []
a1 = [10, 20, 30, 40, 50, 20]
a1 = [] # Clear it!
Tuple Remove all, Clear
Tuple once created, can not be modified. By assigning new empty tuple, it will remove all elements of previous existing tuple.
# Example, Tuple Remove all, Clear
a1 = (10, 20, 30, 40, 50, 20)
a1 = ()
Array Remove all, Clear
Array does not have .clear() method! (as of Python 3.6). Instead create new empty array.
# Example, Array Remove all, Clear
a1 = array.array('l', [10, 20, 30, 40, 50] )
a1.clear() # AttributeError: 'array.array' object has no attribute 'clear'
a1 = array.array('l', [10, 20, 30, 40, 50] )
a1 = array.array('l' ) # Clear it!
AttributeError: 'array.array' object has no attribute 'clear'
Why this error:Are you trying to call .clear() on array? Array does not have .clear() method as of python 3.6.
Solution:Assign new empty array of same type.