Finding maximum value in Python list

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

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

You May Also Like

Leave a Reply

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.