Maximum Value in a List#

In this exercise, you will be writing a function to find the largest item in a list.

Obviously, Python has a built in max() function, but the point here is to practice with list operations, not to use that function.

(Also, be aware that the Python library function max() behaves differently for an empty list or None, but we have not covered exceptions yet, so list_max will have slightly different behavior for these corner cases.)

Setup#

In VS Code, create a file called list_max.py.

Place the following scaffolding into that file:

def list_max(my_list):
    pass

def do_test(my_list):
    print("list_max(", end="")
    if my_list == None:
        print("None) is ", end="")
        pass
    else:
        n = len(my_list)
        print("[", end="")
        for i in range(0, n):
            print(f"{my_list[i]}", end="")
            if i < n - 1:
                print(", ", end="")
                pass
            pass
        print("]) is ", end="")
        pass
    max_of_list = list_max(my_list)
    if max_of_list == None:
        print("None")
        pass
    else:
        print(f"{max_of_list}")
        pass
    pass

def main():
    list1 = [77, 33, 19, 99, 42, 6, 27, 4]
    list2 = [-3, -42, -99, -1000, -999, -88, -77]
    list3 = [425, 59, -3, 77, 0, 36]
    do_test(list1)
    do_test(list2)
    do_test(list3)
    do_test(None)
    do_test([])
    return 0


if __name__ == "__main__":
    main()

Write the Code for list_max#

Fill in list_max so it returns the largest element in the list passed in. If the list has no elements or is None, this function should return None.

Test Locally#

Run your code to see if you get results from the tests in main are 99, -3, 425, None, and None for the five tests provided.

Submit to Gradescope#

Submit your code to gradescope! As always, we’ll be testing against arguments that are different from the ones you can look at here, that suggests you have an issue that these cases didn’t catch but which does exist.