Skip to main content

Python: Remove List items

In Python, there are many methods available on the list data type that help you remove an element from a given list. It have various in-built methods to remove items from the list.

1. Using del statement

The del statement is not a function of List. Items of the list can be deleted using del statement by specifying the index of item (element) to be deleted.

mylist = [1,2,3,4,5]
print("Before deleting the item: ", mylist)

del mylist[1]
print("After deleting the item: ", mylist)

Output

Before deleting the item:  [1, 2, 3, 4, 5]
After deleting the item:  [1, 3, 4, 5]

2. Using remove()

It is the built-in function ,it is used to remove the element .If the element is not present in the list it shows error. This function removes one element at a time from the given list. We can use iterator to remove range of elements.

myList = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]
print("Before removing the item: ",myList)

myList.remove(50)
print("After removing the item: ",myList)

Output: 

Before removing the item:  [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]
After removing the item:  [10, 20, 30, 40, 60, 70, 80, 90, 100, 110, 120]

3. Using clear()

The clear() method will remove all the elements present in the list.

my_list = ['a','b','c','d','e']
print("Before clearing the items: ",my_list)

my_list.clear()
print("After clearing the items: ", my_list)

Output:

Before clearing the items:  ['a', 'b', 'c', 'd', 'e']
After clearing the items:  []

4. Using pop()

It can also be used to remove and return an element from the set, but by default it removes only the last element of the set, to remove element from a specific position of the List, index of the element is passed as an argument to the pop() method.

myList = [1,2,3,4,5,6]
print("Before pop operation: ",myList)

myList.pop()
print("After pop operation: ",myList)
myList.pop()
print("After using pop one more time: ",myList)

Output

Before pop operation:  [1, 2, 3, 4, 5, 6]
After pop operation:  [1, 2, 3, 4, 5]
After using pop one more time:  [1, 2, 3, 4]

Tags
Submitted by devanshi.srivastava on June 9, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.