2
\$\begingroup\$

I was asked to define a function that takes a list as an argument and returns the index of the smallest value.


This is what I came up with:

def index_finder(lst):
    """
    parameters: lst of type list
    returns: index of the lst's smallest value
    """
    for i in range(len(lst)):
        if lst[i]==index(lst):
            print(i)
    return None

def index(lst):
    """
    parameters: lst of type list
    returns: the smallest value of that lst
    """
    if len(lst)==1:
        return lst[0]
    if lst[0]<lst[1]:
        lst.append(lst[0])
    return index(lst[1:])

index_finder([3,2,4,0,1,5,-6,2,5])

This will output the following:

6

As you can see I had to use separate functions in order to get the result. Is there a concise, yet simple way to do this?

By concise I mean short and by simple I mean using only simple functions.

\$\endgroup\$
2
\$\begingroup\$

Yes, there is a concise way to do this, even without a recursive function and that is to use the built-in min function with a custom key:

from operator import itemgetter

def min_index(x):
    return min(enumerate(x), key=itemgetter(1))[0]

The enumerate function adds the indices and the operator.itemgetter ensures that min cares only about the actual value (here it is equivalent to lambda t: t[1]). The [0] at the end gets the index from the minimum tuple.

The usage is almost the same as your function, it returns the value so you have to print it yourself. This is actually good practice because this way you can use the output of the function for other things afterwards.

if __name__ == "__main__":
    print(min_index([3,2,4,0,1,5,-6,2,5]))
    # 6

If you want to use numpy (i.e you are going to do some heavy calculations with these objects), there is a function which does exactly what you want already implemented, numpy.argmin:

import numpy as np

np.argmin([3,2,4,0,1,5,-6,2,5])
# 6
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.