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...
You can determine the
maxval
withmax
:Then get the indices using
enumerate
and a list comprehension:For your example, I get
As per Keyser's suggestion, you could save iterating over the list twice (once to determine
maxval
, once to find matchingindex
es) by doing:Similar to enumerate and list comprehension, you can also use filter:
I tried to do the most Pythonic way as possible
Edit: Ashwini is right. max() needs to be outside the list, so...
Enumerate will help you to get the value and location
output
5 58
10 58
11 58