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

Linda Hamilton
Release: 2024-10-29 18:36:02
Original
915 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!