Python - Remove Item from List - remove()
Python - Remove an Item from List
To remove an item from Python List, you can use the remove()
method on the list with the item passed as an argument.
In this tutorial, we shall go through examples to understand how to use the remove()
function to delete an item from the list.
Syntax of remove()
The syntax of remove()
method is:
mylist.remove(thisitem)
where thisitem has to be removed from mylist.
The remove()
method removes only the first occurrence of the item in the list. Subsequent occurrences remain untouched. At the end of this article, we will also learn how to remove all items with a specific value.
Examples
1. Remove item '5' from the list
In the following example, we have a list with multiple items. The item we would like to remove, 5, is present only once.
Python Program
mylist = [21, 5, 8, 52, 21, 87]
item = 5
# Remove the item
mylist.remove(item)
print(mylist)
Output
[21, 8, 52, 21, 87]
Explanation
- The
remove()
method is called onmylist
with the value5
. - Since
5
is present in the list, it is removed. - The remaining elements are shifted left to fill the gap, and the updated list is printed as
[21, 8, 52, 21, 87]
.
2. Remove item that is present multiple times in the list
In this example, we remove the first occurrence of an item, 21, that is present multiple times in the list.
Python Program
mylist = [21, 5, 8, 52, 21, 87]
item = 21
# Remove the item
mylist.remove(item)
print(mylist)
Output
[5, 8, 52, 21, 87]
Explanation
- The
remove()
method is called onmylist
with the value21
. - Only the first occurrence of
21
is removed. - The list is updated to
[5, 8, 52, 21, 87]
, leaving the second occurrence of21
intact.
3. Remove all occurrences of an item from the list
In this example, we will remove all occurrences of a specific value, 21.
Python Program
mylist = [21, 5, 8, 52, 21, 87]
r_item = 21
# Remove all occurrences of the item
mylist = [item for item in mylist if item != r_item]
print(mylist)
Output
[5, 8, 52, 87]
Explanation
- A list comprehension is used to create a new list that includes only the elements not equal to
r_item
. - Both occurrences of
21
are removed from the list. - The updated list is printed as
[5, 8, 52, 87]
.
4. Remove an item by index using del
Instead of removing an item by value, you can use del
to remove an item by its index.
Python Program
mylist = [21, 5, 8, 52, 87]
index = 2
# Remove the item at index 2
del mylist[index]
print(mylist)
Output
[21, 5, 52, 87]
Explanation
- The
del
statement is used to delete the element at index2
. - The item
8
is removed, and the remaining elements are shifted left to fill the gap. - The updated list is printed as
[21, 5, 52, 87]
.
Summary
In this tutorial of Python Examples, we learned how to remove an item from the list using remove()
, how to remove all occurrences of an item, and how to remove items by index using del
.