Remove from list Python

Previous
Next

In this post, we will see how to remove an element from list in python.

You can remove elements from list in 3 ways.


Using list object’s remove method

Here you need to specify element which you want to remove. If there are multiple occurrences of element, then first occurrence will be removed.

Please note that this is quite slow as it searches for element in the list and then remove the element by its value.
If the element is not present in the list, then it raises ValueError.

list1=["India", 1, "Nepal", 2,5,1,2,3,4,3,2] list1.remove(2) print(list1) list1.remove(9) print(list1)
[‘India’, 1, ‘Nepal’, 5, 1, 2, 3, 4, 3, 2]
—————————————————————————
ValueError Traceback (most recent call last)
in ()
3 print(list1)
4
—-> 5 list1.remove(9)
6 print(list1)

ValueError: list.remove(x): x not in list


Using list object’s pop method

This method takes index of element as input and remove it. It throws IndexError if index is out of range.

list1=["India", 1, "Nepal", 2,5,1,2,3,4,3,2] list1.pop(2) print(list1) list1.pop(14) print(list1)
[‘India’, 1, 2, 5, 1, 2, 3, 4, 3, 2]
—————————————————————————
IndexError Traceback (most recent call last)
in ()
3 print(list1)
4
—-> 5 list1.pop(14)
6 print(list1)

IndexError: pop index out of range


Using operator del

This operator takes index of element as a input and remove the element. del operator also supports removing range of elements from the list.This is clear and fast way of removing elements from the list.

list1=["India", 1, "Nepal", 2,5,1,"France",2,3,4,3,2] del list1[2] print(list1) del list1[4:7] print(list1)
[‘India’, 1, 2, 5, 1, ‘France’, 2, 3, 4, 3, 2]
[‘India’, 1, 2, 5, 3, 4, 3, 2]

That’s all about Python remove from list.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog