Solution Exercise 24

The function max(),  from exercise 13, and the function max_of_three(), from exercise 14, will only work for two and three numbers, respectively. But suppose we have a much larger number of numbers, or suppose we cannot tell in advance how many they are? Write a function max_in_list() that takes a list of numbers and returns the largest one.

def max_in_list(list_):
    # Check if we have anything in the list
    if list_:
        # And make sure there is more than one value
        if len(list_) == 1:
            return list_[0]
        else:
            # Now we know we have at leat two values
            max = list_[0]
            for item in list_[1:]:
                if item > max:
                    max = item
        return max
    else:
        # List was empty so nothing to return
        return None


def main():
    numbers = [16, 4, 7, 11, 18, 3, 16]
    print(max_in_list(numbers))

if __name__ == '__main__':
    main()

Of course, in a real world situation we would use the built in max function:

def main():
    numbers = [16, 4, 7, 11, 18, 3, 16]
    print(max(numbers))

if __name__ == '__main__':
    main()