/  Technology   /  Is there a simple way to delete a list element by value in Python?
Is there a simple way to delete a list element by value in Python

Is there a simple way to delete a list element by value in Python?

 

We can use the list method remove() to delete a list element by value from the given list. The remove() method takes in a value that is to be deleted and performs the operation. 

 

Example:

demo_list=[1,3,5,7,9,11,13,15,17,19]
demo_list.remove(5)
print(demo_list)

Output:

 

Note that this method does not delete all the occurrences of an element, it only deletes the first occurrence of that element. 

 

Example:

demo_list=[1,3,5,5,1]
demo_list.remove(5)
print(demo_list)

Output:

 

We can use list comprehension to remove all the occurrences of an element from a list. 

 

Example:

demo_list=[1,3,5,5,7,9,11]
demo_list= [x for x in demo_list if x!=5]
print(demo_list)

Output:

 

These are the two methods to delete an element by value from a list.

To delete an element by index, we have got the below ways,

  • Using del
  • Using pop()
  • Using slicing

 

To know more about these methods refer to the below articles

Using del,   Using pop(),   Using slicing

 

Leave a comment