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:
-
if str in my_list: # return message -
if "" in my_list: # return message -
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!
any(isinstance(i, str) for i in my_list)anywill returnTrueorFalse, so yes it can be used in anifstatement. the(isinstance(i, str) for i in my_list)is referred to as a generator expression, which will loop overmy_list. As I said before you can't check all the elements of a list without looping over them in some way. By usinganythe loop will quit as soon as a singlestris found, so it saves a bit of time by not continuing on after that, but if there are none, it has to check every member in the list in case the very last one is a string.inwith a list is actually running aforloop to check each element of the list to determine if the given object is "in" the list. There is just no way to avoid aforloop for this instance (whether that loop is one you write, or one happening under the hood).