Remove an Element from a List by Index in Python
Last Updated :
27 Feb, 2024
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.
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)
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)
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)
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}")
Output[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.