Explain Codes LogoExplain Codes Logo

Getting the index of the returned max or min item using max()/min() on a list

python
numpy
argmin
argmax
Nikita BarsukovbyNikita Barsukov·Dec 13, 2024
TLDR

Let's kick things off by locating the index of the peak or valley value in a list using handy built-ins: max(), min() and index(). Keep it simple, Pythonic!

Max index:

# Prepare your list! my_list = [3, 5, 1, 4, 2] # Python goes on a treasure hunt! idx_max = my_list.index(max(my_list)) # "X marks the spot!"

Min index:

# Same list - new goal! my_list = [3, 5, 1, 4, 2] # Python turns into a metal detector! idx_min = my_list.index(min(my_list)) # "Ding Ding! Found it!"

Tip: Use idx_max or idx_min to swiftly navigate the treacherous terrains of your data.

Shifting gear with Numpy

When the terrain gets tough with large datasets, we need some heavy machinery! Say hello to Numpy—a high-performance beast for stuff like this:

import numpy as np # Making list a gym-fit Numpy array values = np.array([3, 5, 1, 4, 2]) # Flexing with maximum idx_max = np.argmax(values) # Faster than Flash! # Flying low with minimum idx_min = np.argmin(values) # Low-score, high-speed!

Numpy biceps are designed for faster operations, without even breaking a sweat (or copying memory).

Wrestling with duplicates

Now, duplicate values in your list can be a tricky rival. But fret not! To wrestle down all indices of the min/max value, tug on this:

# Getting EVERYONE on the podium! indices = [i for i, x in enumerate(my_list) if x == max(my_list)] # "A tie for max!" indices = [i for i, x in enumerate(my_list) if x == min(my_list)] # "Shared glory for min!"

This will present a bouquet of indices basking in the glory of being highest or lowest.

Minimax maneuver with Numpy

When playing with minimax algorithms, it's all about making the right move. That means efficient retrieval of peak or trough indices. Bless Numpy's creators for argmin/argmax, giving the performance edge needed in game trees and decision matrices.

Large datasets - setting the pace

Marathons are different than sprints. For the long haul with large lists, Python's built-in functions tend to lag behind. Numpy powers through with np.argmin() and np.argmax()—true long-distance champs specializing in high-speed operations that can cover distance (large datasets) in record time!

Index-value pairs - twice nice!

Another tasty morsel is to pair the element (delicious cake) with its index (cherry on top) using enumerate():

# Behold the cherry-picking method! min_pair = min(enumerate(my_list), key=lambda pair: pair[1]) min_index, min_value = min_pair # "Got the min and its spot!" max_pair = max(enumerate(my_list), key=lambda pair: pair[1]) max_index, max_value = max_pair # "Caught the max and its hideout!"

A concise way of getting both the value and its index served on a silver platter!

Benchmarking - the speedometer

Nothing like a good old benchmark to test our methods! Observations suggest that Numpy's argmin()/argmax() are the consistent pace-setters, outperforming other techniques, especially with the list size growing. A neat way of knowing how quick is your quick-find!

Fueling up with numpy

To unleash Numpy's power, you need it on your toolbox:

pip install numpy # Command-line charm!

Once you get it, summon it at the start of your script:

import numpy as np # "Ready for duty, sir!"

Python's built-ins are cool and all but when it comes to a drag race, numpy knows how to burn rubber!