In this article we will discuss different ways to remove an elements from list.

Remove an element from List by value using list.remove()

Python’s list provides a member function to remove an element from list i.e.

It removes the first occurrence of given element from the list.

For example,

Suppose we have a list of numbers i.e.

Let’s remove 56 from the given list using list.remove() i.e.

It will remove the first occurrence of 56 from the above lists. Lists contents will be now,

If we try to remove the element that doesn’t exists in list then list.remove() will throw exception.
Therefore before calling list.remove() we should either,

Check if element exists in list i.e.

Or use try / except i.e.

Remove an element from List by Index using list.pop()

In python list’s pop() function will remove the element at given index and also returns the deleted element.
If index is not given then it deletes the last element.

For examples,

We have a list of ints i.e.

Let’s remove element at index 2

List’s contents will be now

Returned value is 12 i.e. the deleted element.

list.pop() and Runtime Error

If list.pop() is called an index that is out of the boundary of List then it will generate a runtime error.
Therefore we should always check the size of list before calling list.pop() i.e.

or Use try / except

Remove an element from List by del

In python del is a keyword and can be used to delete the element in list by index i.e.

It will delete the element at index 2 in list.

If del list[index] is called on an index that is out of the boundary of List then it will generate a runtime error.
Therefore check size of list before calling del i.e.

or Use try / except

Complete example is as follows,

Output:

 

 

Click Here to Subscribe for more Articles / Tutorials like this.