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?
You could just search for the item you want to delete. It is really simple. Example:
letters = ["a", "b", "c", "d", "e"]
letters.remove(letters[1])
print(*letters) # Used with a * to make it unpack you don't have to (Python 3.x or newer)
Output: a c d e
It has already been mentioned how to remove a single element from a list and which advantages the different methods have. Note, however, that removing multiple elements has some potential for errors:
>>> l = [0,1,2,3,4,5,6,7,8,9]
>>> indices=[3,7]
>>> for i in indices:
... del l[i]
...
>>> l
[0, 1, 2, 4, 5, 6, 7, 9]
Elements 3 and 8 (not 3 and 7) of the original list have been removed (as the list was shortened during the loop), which might not have been the intention. If you want to safely remove multiple indices you should instead delete the elements with highest index first, e.g. like this:
>>> l = [0,1,2,3,4,5,6,7,8,9]
>>> indices=[3,7]
>>> for i in sorted(indices, reverse=True):
... del l[i]
...
>>> l
[0, 1, 2, 4, 5, 6, 8, 9]
Use the following code to remove element from the list:
list = [1, 2, 3, 4]
list.remove(1)
print(list)
output = [2, 3, 4]
If you want to remove index element data from the list use:
list = [1, 2, 3, 4]
list.remove(list[2])
print(list)
output : [1, 2, 4]
pop is also useful to remove and keep an item from a list. Where del
actually trashes the item.
>>> x = [1, 2, 3, 4]
>>> p = x.pop(1)
>>> p
2
One can either use del or pop, but I prefer del, since you can specify index and slices, giving the user more control over the data.
For example, starting with the list shown, one can remove its last element with del
as a slice, and then one can remove the last element from the result using pop
.
>>> l = [1,2,3,4,5]
>>> del l[-1:]
>>> l
[1, 2, 3, 4]
>>> l.pop(-1)
4
>>> l
[1, 2, 3]
As previously mentioned, best practice is del(); or pop() if you need to know the value.
An alternate solution is to re-stack only those elements you want:
a = ['a', 'b', 'c', 'd']
def remove_element(list_,index_):
clipboard = []
for i in range(len(list_)):
if i is not index_:
clipboard.append(list_[i])
return clipboard
print(remove_element(a,2))
>> ['a', 'b', 'd']
eta: hmm... will not work on negative index values, will ponder and update
I suppose
if index_<0:index_=len(list_)+index_
would patch it... but suddenly this idea seems very brittle. Interesting thought experiment though. Seems there should be a 'proper' way to do this with append() / list comprehension.
pondering