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 listmax.py
. (No underscore or capitals)
Place the following scaffolding into that file.
Note that in this scaffolding we have chosen not to use a main()
function — instead, the code that in previous exercises we might have included under def main():
we have placed direction in the if __name__ == "__main__":
block. This is just another way to organize a file, and makes no difference to execution.
def list_max(my_list):
pass
# You don't have to change this function
def do_test(my_list):
"""
Prints out list being tested
and result of list_max()
"""
print(f"list_max({my_list}) is: {list_max(my_list)}")
if __name__ == "__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([])
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.