Home > other >  Python loop through a list and execute a function once if value is found
Python loop through a list and execute a function once if value is found

Time:10-28

I want to check a list for any values below a certain number (e.g. check any values below 100) and then execute a function if any values meet this criteria, but I only want to execute the function once, regardless of how many values meet the criteria. I'm having trouble with only executing the function once.

list = [97, 98, 99, 100, 101, 102]

for num in list:
    if num < 100:
        execute_function()

This executes the function every time the value is found. I only want to execute it once and I am drawing a blank on how to do this. Thanks.

CodePudding user response:

You can call any() to test if any of the numbers meets the condition.

if any(num < 100 for num in list):
    execute_function();

CodePudding user response:

break breaks you out of the innermost containing loop (for, while).

for num in list:
    if num < 100:
        execute_function()
        break

Additionally, you could add an action if the condition is not met

for num in list:
    if num < 100:
        execute_function()
        break
else:
    print("no numbers less that 100")

In this case, the else runs if there isn't a break.

CodePudding user response:

I understand your question to mean you want to keep looping if the execute_function has run, you just only want it to run once. If that's true, you could just create a bool variable equal to False that gets set to True when execute_function runs for the first time.

list = [97, 98, 99, 100, 101, 102]

ran_already = False

for num in list:
    if num < 100 and ran_already == False:
        ran_already = True
        execute_function()

CodePudding user response:

from typing import Optional, Union


class Handler:

    @staticmethod
    def check_data(data: Optional[Union[list, tuple]], criteria_value: int) -> bool:
        return any(num == criteria_value for num in data)

    @staticmethod
    def execute_function():
        print('execute')


if __name__ == '__main__':
    uncheck_data = [1, 2, 3]
    criteria = 4
    if Handler.check_data(data=uncheck_data, criteria_value=criteria):
        Handler.execute_function()
    else:
        print('checked, no value meet criteria_value: {}'.format(criteria))
  • Related