How to 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? It seems like the default remove searches the list, but I don't want any search to be performed.
How to 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? It seems like the default remove searches the list, but I don't want any search to be performed.
You probably want pop
:
a = ['a', 'b', 'c', 'd']
a.pop(1)
# now a is ['a', 'c', 'd']
By default, pop
without any arguments removes the last item:
a = ['a', 'b', 'c', 'd']
a.pop()
# now a is ['a', 'b', 'c']
Use del
and specify the element you want to delete with the index:
In [9]: a = range(10)
In [10]: a
Out[10]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [11]: del a[-1]
In [12]: a
Out[12]: [0, 1, 2, 3, 4, 5, 6, 7, 8]
Here is the section from the tutorial.
A quick warning: be wary of modifying a list and iterating over it at the same time.
e.g. can you predict the outcome of this code?
lst = range(10)
for i, x in enumerate(lst):
del lst[i]
print lst