Find the maximum number in a list

problem

Given a list of numbers e.g. [1, 3, 5, 6, 9, 11, 38, 40] we wish to find the maximum number and return it. The numbers are not sorted in any way and the list contains at least 1 element.

SOLUTION

A Python function will do the trick. Let’s write a small program made up from two functions. The main() one which is the entry point of the program and a function find_maximum() that the main() will call.

The find_maximum accepts an argument, the list of numbers.

The definition will be as follows:

				
					def find_maximum(numbers):
     #finds the maximum number in numbers
				
			

The find_maximum accepts the list of numbers that has at least 1 element. Now, in order to find the maximum number, one approach is to use the first element of the list as the maximum and compare it with the rest. We will use a maximum variable to keep the maximum and a for loop to do all the comparison. So the code now becomes as follows:

				
					def find_maximum(numbers):
        maximum = numbers[0] #treat first element as the maximum
        return maximum
				
			

In the case that the list is singleton (having only 1 element), then that element will be the maximum by default.

The code above stores the first element of the list in the maximum variable and simply returns it. Now, let’s add a loop to iterate through the remaining elements of the list. The remaining can be retrieved using the slice notation. If a list numbers contains 10 items and we need all but not the first one, then it can be done with:

				
					numbers[1:]
				
			

Adding it altogether:

				
					def find_maximum(numbers):
        maximum = numbers[0]
        for number in numbers[1:]:
            if number > maximum:
                maximum = number
        return maximum
				
			
The above code iterates through the elements and compares each one with what was stored in maximum. If the current number is greater then the maximum gets updated and so on.
running
Finally, let’s put a main function that will call the find_maximum() with some real example.
				
					def find_maximum(numbers):
    maximum = numbers[0]
    for number in numbers[1:]:
        if number > maximum:
            maximum = number
    return maximum

def main():
    print(find_maximum([2,5,3]))

if __name__ == "__main__":
    main()

				
			

In the above code, we’re calling the function with the list [2,5,3]. The main function will print the result of find_maximum([2,5,3]). That was a small shortcut. To write that simpler, we can introduce a new variable to hold the function’s result as follows:

				
					def main():
        maximum = find_maximum([2,5,3])
        print(maximum)
				
			
output

And running it will give us 5 as expected!

conclusion

Feel free to download the complete solution and experiment with adding negative numbers, floats, etc to the list and inspect the output.

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

Google Analytics Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.

HotJar Cookies

We use Hotjar in order to better understand our users’ needs and to optimize this service and experience. Hotjar is a technology service that helps us better understand our users’ experience (e.g. how much time they spend on which pages, which links they choose to click, what users do and don’t like, etc.) and this enables us to build and maintain our service with user feedback. Hotjar uses cookies and other technologies to collect data on our users’ behavior and their devices. This includes a device's IP address (processed during your session and stored in a de-identified form), device screen size, device type (unique device identifiers), browser information, geographic location (country only), and the preferred language used to display our website. Hotjar stores this information on our behalf in a pseudonymized user profile. Hotjar is contractually forbidden to sell any of the data collected on our behalf.

For further details, please see the ‘about Hotjar’ section of Hotjar’s support site.