Python list remove() function | remove elements by value

You can use the “Python list remove() function” to remove elements (items) from the list. Python lists also have other methods clear(), pop(), and remove() are used to remove items (elements) from a list.

In this tutorial we will see examples of only Python list remove function.

A remove() is an inbuilt function in Python that removes a given elements from the list and does not return any value.

Syntax

list.remove(element)

Note: It removes the first occurrence of the item from the list.

Example of remove element from a list in Python

The first occurrence of 4 is removed from the list.

list1 = [3, 4, 1, 1, 8, 9]
list1.remove(4)
print(list1)

Output: [3, 1, 1, 8, 9]

Remove “a” form the list.

list2 = ['a', 'b', 'c', 'd']
list2.remove('a')
print(list2)

Output: [‘b’, ‘c’, ‘d’]

Removing elements not present in the list

It returns ValueError when the passed elements in the remove() function is not present in the list.

Try deleting a “6” (doesn’t exist) from the list.

list1 = [3, 4, 1, 1, 8, 9]
list1.remove(6)
print(list1)

Output:

Python list remove function elements

Q: How to the Python list remove multiple elements?

Answer: Use a list comprehension with enumerate():

oldlist = ["a", "b", "c", "d"]
removeset = set([1, 3])
print([v for i, v in enumerate(oldlist) if i not in removeset])

Output:

[‘a’, ‘c’]

Q: Will the remove() method remove all list duplicate elements?

Answer: If a list contains duplicate elements, the remove() function only removes the first matching element.

# animals list
animals = ['cat', 'dog', 'dog', 'cow', 'dog']

# remove dog
animals.remove('dog')

print(animals)

Output:

[‘cat’, ‘dog’, ‘cow’, ‘dog’]

Q: How to Remove all occurrences of a value from a list?

Answer: Functional approach: see below code program.

x = [1, 2, 3, 2, 2, 2, 3, 4]
print(list(filter((2).__ne__, x)))

Output:

[1, 3, 3, 4]

Do comment if you have any doubts and suggestions on this tutorial.

Note: This example (Project) is developed in PyCharm 2020.1 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.15.4
Python 3.7
All Python Programs code are in Python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.