## Introduction to finding the minimum or maximum value in a list in Python

This is a classic computer science problem that students are asked to solve in a range of programming languages. You are asked to find the array or list element with the maximum value or the minimum value in a list or array. You need to determine the value itself and its index in the array or list. In this Python article, we will look at various options and give some solutions.

In business computing finding the min, max and average values in lists of numbers is a frequent requirement. Often the data sets can be very large.

The examples below are written in Python 3, you are welcome to copy and paste any of the source code into your Python IDE or editor to experiment with.

These examples should work in earlier Python versions with few modifications, for example, I have used f-strings but these are easily rewritten into earlier styles of Python.

### What is meant by the maximum or minimum value?

The maximum value is the highest or biggest value that exists in the list. Likewise, the minimum value is the smallest or lowest value to be found in the list.

It is worth asking if the data set can have duplicate values. If duplicates are possible then check with the person who set the problem if they want the index of the first instance, the last instance or maybe a list of all the instances of the highest value.

It is also worth asking if the list can contain null or None values. If it can, how should this be handled? There is no fixed answer to this, it depends on the problem scenario.

For example, we could have a year group of students who are due to take an end of term exam. Their scores are captured in a list. This has many duplicate values and also contains some nulls as a few students were sick on the day and failed to take the exam.

### What is a Python List?

In Python, a list is more flexible than arrays in many other programming languages. You can have a list containing many different object types, and in Python, everything is an Object. To create an empty new list use the syntax:

my_list = []

You can create a list containing values with the following syntax:

my_list = [1,3,5,7]

This allows us to create a list of values, in the above example they are all integers but they could also be any other object eg my_names = [‘Kirk’,’Bones’] which is now a list of Python strings.

You can append list items to an existing Python list:

my_list.append(11)

### Python inbuilt functions and lists

As we will see shortly, Python supports many built-in functions for lists, these include len, min and max which will return the length, ie the number of items in the list, min, the minimum value in the list and max, the maximum/highest value in the list.

len(my_list)

max(my_list)

min(my_list)

## The least computing intensive method to find the minimum value in a list.

The first method of returning the minimum or maximum (or indeed average) value in a list might be considered a cheat. In practice cheats like this in commercial python programs and applications can save hours of compute time and therefore money.

If the list is being built up over time while the application is running, maybe as online exams are completed and the scores come in, we just need to test if the new score beats the current min or max. If you want to also compute the average then just maintain the total value and divide by the number of elements.

Here is a simple example which is written in Python 3:

def add_score(new_score:int): global min_score, max_score,total_score,average_score number_list.append(new_score) if not max_score and not min_score: max_score=new_score min_score=new_score elif new_score>max_score: max_score=new_score elif new_score<min_score: min_score=new_score total_score=total_score+new_score average_score=total_score/len(number_list) number_list = [] min_score = None max_score = None total_score = 0 average_score = 0 add_score(10) print(f"min={min_score} max={max_score} average={average_score}") add_score(5) print(f"min={min_score} max={max_score} average={average_score}") add_score(15) print(f"min={min_score} max={max_score} average={average_score}")

This code will produce the following output:

min=10 max=10 average=10.0

min=5 max=10 average=7.5

min=5 max=15 average=10.0

## Finding the min and max values in a list using Pythons built in functions

One of the reasons Python is so popular is because it has a large set of standard built-in functions, this includes min and max and average and standard deviation functions are easily imported. Using these we can easily find the largest number and the smallest number in the list. In Python the max function will find greatest value in list python.

from statistics import mean,median,stdev exam_scores = [7,10,15,20,1] print(min(exam_scores)) print(max(exam_scores)) print(mean(exam_scores)) print(median(exam_scores)) print(stdev(exam_scores))

This code produces the following output:

1

20

10.6

10

7.300684899377592

**BUT**, note we were asked to give the **index value of the maximum/minimum element** and value in the list. The index gives us the position of the maximum value in the Python list. The Python min function and max function also allow us to return the index of the maximum element with the highest value found with the min and max functions, see the next example below.

from statistics import mean,median,stdev exam_scores = [7,10,1,15,20,2] print(f"Todays exam scores are {exam_scores}") print(f"min value is {min(exam_scores)}") index_min = min(range(len(exam_scores)), key=exam_scores.__getitem__) print(f"This is at index {index_min} and its value is {exam_scores[index_min]}") print(f"max value is {max(exam_scores)}") index_max = max(range(len(exam_scores)), key=exam_scores.__getitem__) print(f"This is at index {index_max} and its value is {exam_scores[index_max]}") print(mean(exam_scores)) print(median(exam_scores)) print(stdev(exam_scores))

This produces the following output:

Today’s exam scores are [7, 10, 1, 15, 20, 2]

min value is 1

This is at index 2 and its value is 1

max value is 20

This is at index 4 and its value is 20

9.166666666666666

8.5

7.4139508136125825

**Don’t forget:** In Python (and most programming languages) the array or list index starts at index number zero, with the first item being at index zero, and the second at index number 1 etc. This is generally known as zero-based arrays and you will often hear the index referred to as the subscript value. If you try to access your list with an array index number beyond the end of the array you will get an array subscript out of bounds error message.

In the above example, the position of the min value is shown as being at index 2, but when we look at the list it is the third item in the list for us when we read left to right. This is because, as explained above, Python counts from zero. Therefore the position of the max value would be 4, not 5.

### What is the best way to do this in Python?

If you really just need to find the min or max value and its index then using the built-in Python functions, as shown above, is your best option and certainly the most Pythonic and simplest to read.

## Using NumPy to find the minimum value in a Numpy array

import numpy as np exam_scores = [7,10,1,15,20,2] index_min = np.argmin(exam_scores) np_min = np.min(exam_scores) print(index_min, np_min)

This produces the output:

2 1

## Using Pandas to find the minimum value in a data frame

import pandas as pd exam_scores = [7,10,1,15,20,2] df = pd.DataFrame(exam_scores) print(f"Min value = {df.min().values} at row {df.idxmin().values}")

The code above creates a Pandas DataFrame from the exam_scores Python List we have used in the previous examples. This produces the output:

Min value = [1] at row [2]

Let me know what you think by leaving a comment or question below. I will come back to this and provide some solutions for returning multiple indexes for all the occurrences of either the minimum or maximum values. For example, to answer the question, what was the top score in the exam and which students scored the top score.

**Frequently asked questions:**

**How do you get index of minimum value in list Python?**

Please see the above discussion on the various ways to find the min and max values and their index in a Python list.

**How to find index of max value in list Python?**

As above, this is explained in the above examples using Python 3.

## 0 Comments