Sometimes, we want to remove an element from a list by index with Python.
In this article, we’ll look at how to remove an element from a list by index with Python.
How to remove an element from a list by index with Python?
To remove an element from a list by index with Python, we can use the del
operator.
For instance, we write:
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
del a[-1]
print(a)
to remove the last element by passing in index -1 into the square brackets.
Therefore, a
is [0, 1, 2, 3, 4, 5, 6, 7, 8]
after del
is used.
We can also use del
to remove elements from the starting index to the ending index minus one.
For instance, we write:
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
del a[2:4]
print(a)
to remove elements from a
with index 2 and 3.
Therefore, a
is [0, 1, 4, 5, 6, 7, 8, 9]
after del
is used.
Conclusion
To remove an element from a list by index with Python, we can use the del
operator.