Search code examples
pythonreturnreturn-value

Reducing the amount of return statements (Python)


The function below returns the index within the list list_of_items of the first item that is equal to search_item. If no such items exist the function returns -1.

With a while loop rather than a for loop and not using any break statements nor index method of a list. How can I reduce my function below so that it only contains a single return statement?


Solution

  • With the restriction to a while loop, and not using any break statements (making this seem a lot like a homework question), your best bet is to create a second condition that controls the execution of the loop. For example:

    def my_index(list_of_items, search_item):
        i = 0
        done = False
        return_value = '-1' # I suspect you meant this to be an int, not str
    
        while i < len(list_of_items) and not done:
            if list_of_items[i] == search_item:
                done = True
                return_value = i
            else:
                i += 1
    
        return return_value