Explain Codes LogoExplain Codes Logo

How to find all positions of the maximum value in a list?

python
performance
best-practices
dataframe
Anton ShumikhinbyAnton Shumikhin·Feb 17, 2025
TLDR

Use enumerate with list comprehension to locate all indices of the maximum value in a list. Use max(list) first to discover the max and then retrieve the positions where list entries match it.

nums = [4, 9, 1, 9, 6, 9] # I'm on "maximum" lockdown to find the indices max_indices = [i for i, val in enumerate(nums) if val == max(nums)]

Returns max_indices, a list of the positions of the maximum value in nums.

The Core Algorithm

Improve performance by determining the maximum value before the list comprehension. It avoids computing the max for each element in the list.

# Like storing snacks for a movie, store the max value for later max_value = max(nums) max_indices = [index for index, value in enumerate(nums) if value == max_value]

When dealing with an empty list, use the max() function's default parameter to prevent errors:

nums = [] # A safeguard against the empty-nightmare scenarios! max_value = max(nums, default=None) max_indices = [index for index, value in enumerate(nums) if value == max_value] if max_value is not None else []

To understand maximum value distribution for data analysis, use np.argmax() for NumPy arrays:

import numpy as np nums = np.array([4, 9, 1, 9, 6, 9]) # Handy-dandy NumPy to the rescue! max_value = nums.max() max_indices = np.argwhere(nums == max_value).flatten().tolist()

Sideways, Diagonals, and Other "turns of events"

Playing with multi-dimensional lists

In scenarios involving multi-dimensional lists or custom comparison logic, use the key argument in max() along with lambdas or custom functions.

Save "memory" for good old times

For large lists, using generators can be more memory-efficient:

# Generators: Like fitness instructors for your memory! max_value = max(nums) max_indices = (index for index, value in enumerate(nums) if value == max_value) max_indices = list(max_indices)

Betting on probabilities

In data-heavy contexts, you can adopt probability-based algorithms to estimate the distribution of your maximum values and optimize your search accordingly. Just keep in mind: with great power, comes great responsibility.

User Guide on Best Practices and Compatibility

Staying in tune with Python 3

All solutions are Python 3 compatible as leveraging modern features and following best practices help not only in coding efficiency but also in enhancing maintainability.

Tapping into the power of libraries

It's often beneficial to utilize libraries such as NumPy for specialized tasks, particularly when dealing with large datasets or numerical computations.

Community Verification Stamp

The community often upvotes solutions that they've tested and found to be efficient and immediately applicable. Meeting these expectations goes a big way in earning that community seal of approval!