Home > Net >  How can I write a function that doesn't print out uppercase words from the list?
How can I write a function that doesn't print out uppercase words from the list?

Time:12-02

I've a list ["ABC", "JAVA", "Python", "user", "CODE"] and I want the functions print out ["Python", "user"].

Here is my progress so far:

def no_upper(my_list : list):
    new_list = my_list
    for word in my_list:
        if word.isupper():
            my_list.remove(word)
        return new_list
if __name__ == "__main__":
    my_list = ["ABC", "JAVA", "Python", "user", "CODE"]
    new_list = no_upper(my_list)
    print(new_list)   

 

CodePudding user response:

If you objective is to "remove" words written entirely in capital letters:

lst = ["ABC", "JAVA", "Python", "user", "CODE"]
[x for x in lst if x != x.upper()]

OUTPUT

['Python', 'user']

CodePudding user response:

  • Enclose your strings in quotes.
  • Your function tries to modify my_list rather than actually building your new_list. Just build the new list and return it without trying to remove the items from the input -- modifying a list you're iterating over will usually have unexpected/buggy results, and even if it worked to do that, there's no good reason to mess around with the caller's data that way.
>>> def no_upper(my_list: list) -> list:
...     return [word for word in my_list if not word.isupper()]
...
>>> no_upper(["ABC", "JAVA", "Python", "user", "CODE"])
['Python', 'user']

CodePudding user response:

Try with a list like this:

my_list = ["ABC", "Java", "Python"]

Unless Python will raise an UnboundLocalError, since ABC without quotes ('') or double quotes ("") is parsed as a variable, but there's no ABC variable in your program.

You can also use inline syntax to solve your problem, like this:

def noUpper(l: list):
    return [x for x in list if not x.isupper()]
  • Related