How do I remove an element from a list by index in Python?
I found the list.remove
method, but say I want to remove the last element, how do I do this?
This depends on what you want to do.
If you want to return the element you removed, use pop()
:
>>> l = [1, 2, 3, 4, 5]
>>> l.pop(2)
3
>>> l
[1, 2, 4, 5]
However, if you just want to delete an element, use del
:
>>> l = [1, 2, 3, 4, 5]
>>> del l[2]
>>> l
[1, 2, 4, 5]
Additionally, del
allows you to use slices (e.g. del[2:]
).