How to remove an Item from Python List?

Python – Remove an Item from List

To remove an item from Python List, you can use remove() method on the list with the item passed as argument.

In this tutorial, we shall go through examples, to understand how to use 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. The subsequent occurrences are untouched. At the end of this article, we will also learn to remove all of those items with a specific value.

Examples

1. Remove item ‘5’ from the list

In the following example, we have a list with multiple items. And 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)
Run Code Copy

Output

[21, 8, 52, 21, 87]

The item is removed and the index of subsequent items is reduced by 1.

2. Remove item that is present multiple times in the list

In the following example, we have a list with multiple items. And the item we would like to remove, 21, is present twice.

Python Prgoram

mylist = [21, 5, 8, 52, 21, 87]
item = 21

# Remove the item
mylist.remove(item)

print(mylist)
Run Code Copy

Output

[5, 8, 52, 21, 87]

The item is present twice, but only the first occurrence is removed.

3. Remove all the occurrences of an item from the list

In this example, we will remove all the elements that match a specific value, 21.

Python Program

mylist = [21, 5, 8, 52, 21, 87]
r_item = 21

# Remove the item for all its occurrences
for item in mylist:
    if(item==r_item):
        mylist.remove(r_item)

print(mylist)
Run Code Copy

Output

[5, 8, 52, 87]

Summary

In this tutorial of Python Examples, we learned how to remove an item from the list, could be first occurrence or all occurences.

Related Tutorials

Code copied to clipboard successfully 👍