/  Technology   /  How to remove an element from a list by index?

How to remove an element from a list by index?

How to remove an element from a list by index?

 

In this article let’s discuss various ways of deleting an element from a list by index.

 

  • Using pop()
  • Using slicing
  • Using del keyword

Using pop():

In this in-built list method, we pass the index of the element which we wish to delete as a parameter. 

list.pop(index)

If the list is empty or if the index is out of range, this method raises the IndexError.

It’s always a good practice to check whether the index is valid or not before using this method to avoid errors.

Using slicing:

Slicing helps in obtaining a substring, sub-tuple, or sublist from any given iterable like a string, tuple, or list respectively.

The syntax of slicing is [start_at : stop_before: step]

  • start_at is the index of the first item to be returned (included).
  • stop_before is the index of the element before which the iteration stops (not included).
  • step is the stride or the jump between any two items.

Note: To learn more about slicing notation in python, refer to the article below.

https://www.i2tutorials.com/the-slice-notation/

Using del keyword:

We can delete an element using this del keyword by declaring it as

 

del sample_list[index]

 

If the list is empty or if the index is out of range, this method raises the IndexError. So in this method also it’s better to check if the given index is valid or not to avoid errors.

Leave a comment