Index of max and min values in Python

To get indexes of min and max values in a list, first, you have to use the min and max functions to find the smallest and largest numbers. Next, use the index function of the list to find out the index of these numbers.

numbers = [5, 1, 23, 1, 23, 53, 78, 43, 78]

min_value = min(numbers)
max_value = max(numbers)

min_index = numbers.index(min_value)
max_index = numbers.index(max_value)

print('Index of min value is: ' + str(min_index))
print('Index of max value is: ' + str(max_index))

This code will display the following result:

Index of min value is: 1
Index of max value is: 6

In the list, the smallest number is 1, and the largest 78. Inside the list, each of these numbers occurs twice.

  • The smallest have indexes: 1 and 3.
  • The largest have indexes: 6 and 8.

The code will return only the first indexes, which are 1 and 6.

Get indexes of all min and max values

If you want to get all indexes of the smallest and largest values, you can search for min and max values and then use them inside the for loop to find all indexes.

Here’s how it works:

numbers = [5, 1, 23, 1, 23, 53, 78, 43, 78]

min_indexes = [i for i, x in enumerate(numbers) if x == min(numbers)]
max_indexes = [i for i, x in enumerate(numbers) if x == max(numbers)]

print('Indexes of min values are: ' + str(min_indexes))
print('Indexes of max values are: ' + str(max_indexes))

This code will add indexes of all smallest numbers into one list, and largest into another. If you print them, you are going to get the following result.

Indexes of min value are: [1, 3]
Indexes of max value are: [6, 8]

Min and max indexes with Numpy

Another way you can get indexes is by using a module, called NumPy. This module is used for scientific computing in Python.

import numpy as np

numbers = [5, 1, 23, 1, 23, 53, 78, 43, 78]

min_index = np.argmin(numbers)
max_index = np.argmax(numbers)

print('Index of min value is: ' + str(min_index))
print('Index of max value is: ' + str(max_index))

If you run this code, you are going to get the first indexes of min and max values.

Index of min value is: 1
Index of max value is: 6