Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the max number(s) in a list with tied numbers

So say I have a list like:

my_list = [12, 13, 51, 21, 22, 58, 45.1, 34.2, 56, 6, 58, 58] 

So the max number in this is obviously 58, but I don't just want to return one 58, I want a list of all the indexes that have that max number.

Basically for this I want the result [5, 10, 11]

I know that if I want the max number I can do my_list.index(max(my_list)) but that will simply give me the first index.

Any tips? Also, I want to stick to simple methods such as sort, max, len, etc...

like image 616
user3324536 Avatar asked Feb 18 '14 17:02

user3324536


People also ask

How do you find the maximum number in a list using a loop?

Use temp variable and if statement to find the largest number in a list Python using for loop. Writing your own logic is easy, use temp variable to assign the first value of the list then swap it with the next large number.

How do you find the max number in a list in Python?

In Python, there is a built-in function max() you can use to find the largest number in a list. To use it, call the max() on a list of numbers. It then returns the greatest number in that list.

How do you find the largest number in a while loop in Python?

Initialize an empty list lst = [] . Read each number in your python program using a for loop . In the for loop append each number to the list. Use built-in python function max() to find the largest element in a list.


1 Answers

You can determine the maxval with max:

maxval = max(my_list)

Then get the indices using enumerate and a list comprehension:

indices = [index for index, val in enumerate(my_list) if val == maxval]

For your example, I get

maxval == 58
indices = [5, 10, 11]

As per Keyser's suggestion, you could save iterating over the list twice (once to determine maxval, once to find matching indexes) by doing:

maxval = None
for index, val in enumerate(my_list):
    if maxval is None or val > maxval:
        indices = [index]
        maxval = val
    elif val == maxval:
        indices.append(index)
like image 65
jonrsharpe Avatar answered Oct 11 '22 17:10

jonrsharpe