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

How to remove an element from a list by index in python?

 

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.

 

Example:

list = [1,3,5,7,9,11]
print("The Original List is", str(list))

list.pop(4)
print("The Final List is", str(list))

output:

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.

 

Example:

list = [1,3,5,7,9,11]
print("The Original List is", str(list))

index = 4

list = list[:index] + list[index+1 : ]
print("The Final List is", str(list))

output:

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

 

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.

 

Example:

list = [1,3,5,7,9,11]
print("The Original List is", str(list))

del list(4)
print("The Final List is", str(list))

output:

Leave a comment