Remove Element From List In Python

In this post, We will see different techniques for how to remove element from list in python. so let’s get started.

1. Remove Element By Value

Remove method of python list expects an element as an argument and removes its first occurrence from the list.

# A list containing some elements
>>> x = ["Apple","Orange","Banana","Apple"]
# Remove first occurrence of apple element from the list
>>> x.remove("Apple") 
>>> x
['Orange', 'Banana', 'Apple'] # first occurrence of apple is removed

It raises ValueError if element is not present.

>>> x = ["Apple","Orange","Banana","Apple"]
# Remove An Invalid Element
>>> x.remove("Cucumber")

So its better to wrap the code inside the try-except block

# Wrap the code inside the try-except
>>> try:
	x.remove("cucumber")#remove element from list in python
	print("Element Does not exist")

Element Does not exist

2. Remove Element By Index

The pop() method of python list returns and remove the element at the given index.

If no index is given it removes the last element.

# program to Remove Element From List In Python by its index
>>> x = ["Apple","Orange","Banana","Apple"]
# Remove the element at index 2
>>> x.pop(2)
>>> x
['Apple', 'Orange', 'Apple']
# remove the last element of the list
>>> [1,2,3,4].pop()

3. Remove All Occurrences

The List Comps in python are a more concise way to create lists. It also provides more readability as well as saves the few lines of code.

In this code example, we will use them to remove all the occurrences of an element from the list.

def remove(array,element):
    Function to Remove all occurances of Character From String In Python
    return [i for i in array if i!= element]

x = ["Apple","Orange","Banana","Apple"]
print(remove(x,"Apple"))# remove all apples

Here is the output of above code

Output :

Output of code to Remove Element From List In Python

4. Clear The List

The clear() method of the python list removes all the content from the list.

>>> x =  ["Apple","Orange","Banana","Apple"]
>>> x.clear() # Clear the list
>>> x

That’s wrap for this tutorial.

Also, read about how to remove duplicates from the list.

Leave a Reply