how to find index of min and max value of a int array Python

12,153

Solution 1

def minmaxloc(num_list):
    return num_list.index(max(num_list)), num_list.index(min(num_list))

print(minmaxloc(a))

Solution 2

Use numpy's argmin and argmax methods:

import numpy as np
def minmaxloc(num_list):
    return np.argmin(num_list), np.argmax(num_list)
A= [1,1,8,7,5,9,6,9]
print(minmaxloc(A))
Share:
12,153
bryan tetris
Author by

bryan tetris

Updated on June 28, 2022

Comments

  • bryan tetris
    bryan tetris almost 2 years

    Hello I want to find the first index of the max and min value of an array of integer.

    my code returns all the index in case of duplicate values ...

    A= [1,1,8,7,5,9,6,9]
    def minmaxloc(num_list):
      for i,y in enumerate(num_list):
        if y ==max(num_list) or y==min(num_list):
          print i
    minmaxloc(A)
    

    output: 0 1 5 7

    what i want : (0,5)

    thanks for your help.

    • anishtain4
      anishtain4 about 6 years
      import numpy as np; (np.argmin(A),np.argmax(A))
    • Ahmed Fasih
      Ahmed Fasih about 6 years
      The top answer in the question you were pointed to isn't that great since it sweeps over the array potentially twice. The 2nd answer, stackoverflow.com/a/2474238/500207 is better in this regard. Ideally you'd be able to calculate the max and min in a single sweep, but neither Python or Numpy provide a minmax :(
  • bryan tetris
    bryan tetris about 6 years
    Thanks for help! It works fine But I want to use enumerate
  • Merlin1896
    Merlin1896 about 6 years
    Why the downvote though? Can you elaborate why you need enumerate? It seems there is more to the story.