pythondefault-value

Is it possible to have a default value that depends on a previous parameter?


Suppose I want to write a recursive binary search function in Python. The recursive function needs to get the start and end of the current search interval as parameters:

def binary_search(myarray, start, end): ...

But, when I call the actual function from outside, I always start at 0 and finish at the end of the array. It is easy to make 0 a default value for start, but how can I write a default value for end? Is it possible to write something like:

def binary_search(myarray, start=0, end=len(myarray)): ...

?


Solution

  • The common idiom* is:

    def binary_search(myarray, start=0, end=None):
        if end is None:
            end = len(myarray)
    

    *(usually used to avoid a mutable default argument value, like here: https://stackoverflow.com/a/41686973/5052365)