pythonlistremove-if

Remove all values "Home " from scraped list of names


I have a list of names I have scraped from a website. In that list, there are some observations that are not names but are called "Home ". I can remove them by uni_name.pop(), but this is not easily repeatable.

How do I remove all values from the list that is "Home " at once?

Thank you in advance!

I tried writing this:

uni_name(filter(Home    ).__ne__, uni_name)

But it gave me an NameError: name 'Home' is not defined


Solution

  • To remove all "Home"s (ignoring any number of leading/trailing spaces), the Pythonic way is to use a list comprehension.

    >>> uni_name = ["hello", "Home          ", "   Home", "World"]
    >>> uni_name = [name for name in uni_name if name.strip() != "Home"]
    >>> print(uni_name)
    ['hello', 'World']