Home > Backend Development > Python Tutorial > How to Efficiently Find the Index of Max/Min Values in Python Lists?

How to Efficiently Find the Index of Max/Min Values in Python Lists?

Barbara Streisand
Release: 2024-10-29 18:24:14
Original
657 people have browsed it

 How to Efficiently Find the Index of Max/Min Values in Python Lists?

Getting the Index of Max/Min Values Returned by max()/min() on Lists

When using Python's max() and min() functions on lists for algorithms like minimax, determining the index of the returned maximum or minimum value is often necessary.

Problem:

You need to find the index of the element in a list that corresponds to the max() or min() value returned, to identify which move produced that value.

Solution:

To retrieve the index of the min() value, utilize the following code:

<code class="python">index_min = min(range(len(values)), key=values.__getitem__)</code>
Copy after login

This method eliminates the need for modules like operator or enumerate, and it also outperforms solutions involving itemgetter().

For numpy arrays, consider using:

<code class="python">import numpy as np
index_min = np.argmin(values)</code>
Copy after login

This is faster if the list is large enough and memory consumption is acceptable.

Benchmark:

The benchmark below compares the efficiency of the two proposed solutions:

[Image showing a graph with runtimes for the different methods]

The blue line represents the pure Python solution, while the red line uses numpy. The black line is the reference implementation using itemgetter().

For large lists, the numpy solution is significantly faster. However, for smaller lists, the pure Python solution may be more efficient.

The above is the detailed content of How to Efficiently Find the Index of Max/Min Values in Python Lists?. 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