List method clear() in Python
The list method clear() used to remove all elements from the list but it does not delete the list object.
Syntax
 1 <list>.clear()
list : a list object to remove all elements
List method clear()
 1 list = [1, 2, 3, 4]
 2 
 3 print("An elements before clear : ", list)
 4 
 5 list.clear()
 6 list.append(10)
 7 print("A list after appending new element : ", list)
In the above example, a list object is define with initial number values. An initial list element is printed on console. A list clear() method is called for list object that remove all the elements from the list. A new element is appended by using append() method that will be printed on console.
Output
 1 An elements before clear :  [1, 2, 3, 4]
 2 A list after appending new element :  [10]

Example 2

Example 2
 1 list = ["First", "Second", "Third"]
 2 
 3 print('An original list :', list)
 4 list.clear()
 5 
 6 # append element
 7 list.append('String')
 8 print('Resulting list :', list)
In the above example, a list of string is define an initialize with three elements. A list object print using print() method and clear() which will remove all element and make an empty list. A new element appended and print updated list.
Output
 1 An original list : ['First', 'Second', 'Third']
 2 Resulting list : ['String']
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us