Examples of how to remove an element from a list in python
Remove an element using del()
To remove an element for a given index, a solution is to use the function del:
>>> L1 = ['a','b','c','d','e','f']>>> del L1[3]>>> L1['a', 'b', 'c', 'e', 'f']
Remove the last element
>>> del L1[-1]>>> L1['a', 'b', 'c', 'e']
Remove the first element
>>> L1 = ['a','b','c','d','e','f']>>> del L1[0]>>> L1['b', 'c', 'd', 'e', 'f']
Remove for a range of indexes
>>> L1['a', 'b', 'c', 'e']>>> del L1[1:3]>>> L1['a', 'e']
Trying to remove an element with an index out of range will return the following message:
>>> del L1[7]Traceback (most recent call last):File "<stdin>", line 1, in <module>IndexError: list assignment index out of range
Remove an element for a given value
>>> l = ['a', 'b', 'c', 'd', 'a']>>> while 'a' in l:... del l[l.index('a')]...>>> l['b', 'c', 'd']
Remove an element with remove()
To remove an element for a given value, another solution is to use the function remove (Note: this function only remove the first occurrence):
>>> l = ['a', 'b', 'c', 'd', 'a']>>> l.remove('a')>>> l['b', 'c', 'd', 'a']
to remove all elements:
>>> l = ['a', 'b', 'c', 'd', 'a']>>> while 'a' in l:... l.remove('a')...>>> l['b', 'c', 'd']
Remove an element with a for loop
It is also possible to filter a list in python using a for loop:
>>> l = ['a', 'b', 'c', 'd', 'a']>>> l = [i for i in l if i != 'a']>>> l['b', 'c', 'd']
Remove all elements in a list
Remove all elements using del:
>>> l = ['a', 'b', 'c', 'd', 'a']>>> del l[:]>>> l[]
using clear():
>>> l = ['a', 'b', 'c', 'd', 'a']>>> l.clear()>>> l[]
References
| Links | Site |
|---|---|
| del | Python doc |
| How to remove an element from a list by index in Python? | stackoverflow |
| Is there a simple way to delete a list element by value in python? | stackoverflow |
