Delete all Elements in List Python

Delete all elements in list Python | In Python, there are many methods available on the list data type that help you remove all the elements from a given list. In this post, we will discuss how to remove all items or elements from the list using clear(), del statement, and slice operator. We will take the list while declaring the variables then the Python program removes all the elements from the list. Finally, the new list will be displayed on the screen.

Remove all items from List in Python

Using clear() method

Python dictionary method clear() removes all the elements from the list. It clears the list completely and returns nothing. It does not require any parameter and returns no exception if the list is already empty. The clear() method only empties the given list.

Syntax: list_name.clear()

# Python program to delete all elements in list

# take list
my_list = ['C', 'Java', 'Python', 'Javascript', 'Know Program']

# printing original list
print('List:', my_list)

# removed all item from the list
my_list.clear()

# print list after item deletion
print('New list:', my_list)

Output:-

List: [‘C’, ‘Java’, ‘Python’, ‘Javascript’, ‘Know Program’]
New list: []

Using del Statement

The del operator removes the item or an element at the specified index location from the list, but the removed item is not returned, as it is with the pop() method. So essentially, this operator takes the item’s index to be removed as the argument and deletes the item at that index.

Syntax: del list_name

# Python program to delete all elements in list

# take list
my_list = ['C', 'Java', 'Python', 'Javascript', 'Know Program']

# printing original list
print('List:', my_list)

# removed all item using del statement
del my_list[:]

# print list after item deletion
print('New list:', my_list)

Output:-

List: [‘C’, ‘Java’, ‘Python’, ‘Javascript’, ‘Know Program’]
New list: []

Using Slice Operator

The slice() function returns a slice object. A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end. You can clear the entire list by assignment of an empty list to the slice, i.e., a[:] = []

# Python program to delete all elements in list

# take list
my_list = ['C', 'Java', 'Python', 'Javascript', 'Know Program']

# printing original list
print('List:', my_list)

# removed all item using slicing
my_list[:] = []

# print list after item deletion
print('New list:', my_list)

Output:-

List: [‘C’, ‘Java’, ‘Python’, ‘Javascript’, ‘Know Program’]
New list: []

Also See:- Python Remove First Element from List

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *