Categories
Python Answers

How to remove all occurrences of a value from a list with Python?

Spread the love

Sometimes, we want to remove all occurrences of a value from a list with Python.

In this article, we’ll look at how to remove all occurrences of a value from a list with Python.

How to remove all occurrences of a value from a list with Python?

To remove all occurrences of a value from a list with Python, we can use the filter function.

For instance, we write

x = [
    1,
    2,
    3,
    2,
    2,
    2,
    3,
    4,
    ]
y = list(filter(lambda a: a != 2, x))

to call filter with a function that filters out all values in x that isn’t 2 and x itself.

We convert the iterable object returned by filter into a list with list.

Conclusion

To remove all occurrences of a value from a list with Python, we can use the filter function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *