Search code examples
pythonstringlistany

How to check whether a Python list contains ANY string as an element


So, I was working on a Python function that receives a numeric list as a parameter and processes it, just like this example:

def has_string(myList: list) -> str:

    # Side cases
    if myList == []:
        return "List shouldn't be empty"

    if myList contains any str object:  # Here's the problem
        return "List contains at least one 'str' object"

    return "List contains only numeric values"

I've tried some approaches, like:

  1.  if str in my_list:     # return message
    
  2.  if "" in my_list:      # return message
    
  3.  if my_list.count(""):  # return message
    

I did not want to create a for loop and check each item one by one. I wanted to avoid passing through all the items just to tell whether or not my list contains a string.

As I mentioned before, I've tried some different ways to check it within the if block, but none of them worked. The program still continued to process the list even though there was a condition to stop it.

Any help is greatly appreciated, thanks in advance!


Solution

  • all() stops at the first item evaluates to False. Basically:

    if all(isinstance(x, (int, float)) for x in my_list):
        print("all numbers!")
    else:
        print("not all number!")
    

    And using these C-level functions instead of comprehensions should be more performant:

    from itertools import repeat
    if all(map(isinstance, my_list, repeat((int, float)))):
        print("all numbers!")
    else:
        print("not all number!")