Home  >  Article  >  Backend Development  >  How can I Get the Index of the Maximum or Minimum Value in a List Using Python?

How can I Get the Index of the Maximum or Minimum Value in a List Using Python?

Linda Hamilton
Linda HamiltonOriginal
2024-10-29 18:36:02909browse

How can I Get the Index of the Maximum or Minimum Value in a List Using Python?

Finding the Index of Maximum or Minimum Item Using max()/min() on a List

When implementing a minimax algorithm, it becomes necessary to determine the index of the maximum or minimum value obtained from the max() or min() functions. However, these functions only return the value itself.

To retrieve the index, one can employ the following technique:

<code class="python">values = [3, 6, 1, 5]
index_min = min(range(len(values)), key=values.__getitem__)</code>

This approach iterates through the indices of the values list, utilizing the getitem method to compare each element with the candidate minimum value. The index_min variable captures the index of the actual minimum value.

Alternatively, for dealing with NumPy arrays:

<code class="python">import numpy as np
values = np.array([3, 6, 1, 5])
index_min = np.argmin(values)</code>

Using NumPy offers performance benefits, especially for larger lists or arrays, due to its optimized routines. However, it requires an additional import and may incur a memory copy cost if the input is a pure Python list.

The above is the detailed content of How can I Get the Index of the Maximum or Minimum Value in a List Using Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn