Remove an element from a list using its index in Python
This post will discuss how to remove an element from a list using its index in Python.
1. Using list.pop() function
The simplest approach is to use the list’s pop([i]) function, which removes an element present at the specified position in the list. Note that it raises an IndexError if the list is empty.
|
1 2 3 4 5 6 7 8 9 10 |
if __name__ == '__main__': l = [1, 2, 3, 4, 5] n = 2 value = l.pop(n) print("Removed value", value) # 3 print("Modified list", l) # [1, 2, 4, 5] |
2. Using del statement
Another efficient way to remove an element from a list using its index is the del statement. It differs from the pop() function as it does not return the removed element. It also raises an IndexError if the list is empty.
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': l = [1, 2, 3, 4, 5] n = 2 del l[n] print("Modified list", l) # [1, 2, 4, 5] |
3. Using Slicing
You can even use slicing to remove an element from a list using its index. This can be done using the expression l[:] = l[:n] + l[n+1:], where l is your list, and n is the index whose value is to be removed. This approach is not recommended as it is verbose and constructs multiple copies of the list.
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': l = [1, 2, 3, 4, 5] n = 2 l[:] = l[:n] + l[n+1:] print("Modified list", l) # [1, 2, 4, 5] |
That’s all about removing an element from a list using its index in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)