Removing items from a list in Python
Start your free 7-days trial now!
There are three main ways to remove an item from a list in Python:
Method | Description |
---|---|
| removes the element at a given index from the list |
removes the element at the given index from a list and then returns the removed value | |
removes the first occurrence of the element with the specified value |
del statement
The del
statement is a simple way to remove an item at a particular position in the list:
['potato', 'carrot']
Pop method
The list.pop(~)
method allows you to use the value of an item after you remove it from the list:
At fav_animals.pop()
we remove 'bird'
from list fav_animals
and return it. Then we use this return value as an input to norm_animals.append(~)
and 'bird'
is added to the norm_animals
list.
Remove method
The list.remove(~)
method allows you to remove an element from a list based on its value. This is useful when you do not know the position of the element on the list:
The remove method only deletes the first occurrence of the value in the list. To remove all occurrences you would need to use a for
loop.