tags:

views:

4454

answers:

3

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.

+8  A: 

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']
Jarret Hardie
Don't forget pop(-1). Yes, it's the default, but I prefer it so I don't have to remember which end pop uses by default.
S.Lott
Good point... that does increase readability.
Jarret Hardie
+10  A: 

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.

unbeknown
Thanks, what's the difference between pop and del?
Joan Venge
del is overloaded. For example del a deletes the whole list
Brian R. Bondy
another example del a[2:4], deletes elements 2 and 3
Brian R. Bondy
pop() returns the element you want to remove. del just deletes is.
unbeknown
A: 

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
John Fouhy
Um. Your answer is not an answer to the original question. If you feel the advice is needed, include an actual answer.
ΤΖΩΤΖΙΟΥ