Algorithm for finding smallest value in list (Python)

As a small coding exercise I will write some lines of Python code that find the minimum value in a list and return it. In Python, this can be done with a build-in default function named min(). I avoid using this function on purpose.

The function below is implemented in Python and returns a minimum value of a list
# calling the function "findMinimumValue"
def findMinimumValue( listObj ):
    # set first entry as lowest value to start with
    minVal = listObj[0]
    # cycle through each position in the list
    for i in range(0,len(listObj)):
        # if this value is smaller than current minVal then update minVal
        if listObj[i] < minVal:
            minVal = listObj[i]
    # return minVal
    return minVal
Testing function on a test list
# defining test list
testList = [-1,-2,-3.3,-5,-5.001,0,1,10,1000]
# apply findMinimumValue
findMinimumValue(testList)
-5.001
The same could have been achieved using the min() function from Python base library
min(testList)
-5.001

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Close

Meta