0

I'm checking a string against a large list of strings (approx. 400k+). It seems to be running far quicker than I thought it would to check against these. As such, I want to count how many strings are being iterated through to check if it is functioning properly or not, checking against the full list before confirming a non-match.

My function operates like so:

if any(string_to_check in string for string in list_of_strings):
        print("String Matched:" + string_to_check)
        return True
    else:
        print("String Not Matched:" + string_to_check)
        return False

How could I add to this, to see how many strings in the list_of_strings are iterated through before matching or not matching?

Thanks in advance.

MOK_Z
  • 25
  • 6
  • there are about 1.5+ million hits for `python count items in list if string matches site stackoverflow.com` in the search engine of my choice - you probably want to check some of them if the 2 given duplicates do not statisfy your needs. – Patrick Artner Dec 19 '22 at 09:51
  • 1
    The reason "it runs far quicker" is that `any()` short circuits - if will not check ALL things, but terminate as soon as _one_ is found. Hence it is not usable for "counting" only to check if at least 1 hit is given. If _none_ matches it will search through all of them though. See [is-the-shortcircuit-behaviour-of-pythons-any-all-explicit](https://stackoverflow.com/questions/14730046/is-the-shortcircuit-behaviour-of-pythons-any-all-explicit) for more on that – Patrick Artner Dec 19 '22 at 09:52
  • 1
    The list (list_of_strings) isn't hashed. Therefore the search is likely to be sequential. You can deduce the number of comparison by finding a matched string's index. – DarkKnight Dec 19 '22 at 09:54
  • @PatrickArtner - I'm aware of that, regarding the any(). Sorry if I didn't want to make that clear. So there's no way of checking how many are looked through before terminating that you know of? Unfortunately, my search engine only shows results on how to count list items. Sorry if there is a duplicate question with the same specifics. I haven't seen it. – MOK_Z Dec 19 '22 at 10:04
  • @Fred - Ok sure! That seems like a reasonable solution, thanks. – MOK_Z Dec 19 '22 at 10:05

0 Answers0