Remove an Element from a List by Index in Python
We are given a list and an index value. We have to remove an element from a list that is present at that index value in a list in Python. In this article, we will see how we can remove an element from a list by using the index value in Python.
Example:
Input: [1, 2, 3, 4, 5], index = 2 Output: [1, 2, 4, 5] Explanation: Element present in 2nd index is removed i.e, 3
Remove an Element from a List by Index in Python
Below, are the methods of remove an element from a list by using the index value in Python.
- Using List Comprehension
- Using del keyword
- Using remove() Function
- Using pop() Function
Remove an Element from a List by Index Using List Comprehension
In this example, below code uses list comprehension to create a new list (`updated_list`) excluding the element at index 2 from the original list [1, 2, 3, 4, 5]. The output is [1, 2, 4, 5].
Python3
original_list = [ 1 , 2 , 3 , 4 , 5 ] index_to_remove = 2 updated_list = [element for i, element in enumerate (original_list) if i ! = index_to_remove] print (updated_list) |
[1, 2, 4, 5]
Remove an Element from a List by Index Using the del keyword
In this example, below code utilizes the `del` keyword to remove the element at index 2 from the `original_list` [1, 2, 3, 4, 5], resulting in the modified list [1, 2, 4, 5].
Python3
original_list = [ 1 , 2 , 3 , 4 , 5 ] index_to_remove = 2 del original_list[index_to_remove] print (original_list) |
[1, 2, 4, 5]
Remove an Element from a List by Index Using remove() Function
In this example, below code employs the `remove()` function to eliminate the element with the value 3 from the `original_list` [1, 2, 3, 4, 5], yielding the updated list [1, 2, 4, 5].
Python3
original_list = [ 1 , 2 , 3 , 4 , 5 ] value_to_remove = 3 original_list.remove(value_to_remove) print (original_list) |
[1, 2, 4, 5]
Remove an Element from a List by Index Using pop() Function
In this example, below In this code, the `pop()` function removes the element at index 2 from the `original_list` [1, 2, 3, 4, 5], modifying the list to [1, 2, 4, 5], and the removed element (3) is printed separately.
Python3
original_list = [ 1 , 2 , 3 , 4 , 5 ] index_to_remove = 2 removed_element = original_list.pop(index_to_remove) print (original_list) print (f "Removed element: {removed_element}" ) |
[1, 2, 4, 5] Removed element: 3
Conclusion
In conclusion , Python provides several methods to remove elements from a list by index, each with its own advantages and use cases. Whether you prefer a concise list comprehension, the in-place modification with the del
keyword, or the specialized remove()
and pop()
functions, understanding these techniques will help you choose the most appropriate method for your specific programming needs.