  Python | The maximum and minimum position of an item in the list

Python Methods and Functions

Examples :

Input: 3, 4, 1, 3, 4, 5 Output: The maximum is at position 6 The minimum is at position 3

The naive approach would be to traverse the list and keep track of the lows and highs along with their indices. We have to do N comparisons for the minimum and simultaneously N comparisons for the maximum.

Python built-in function allows us to find it in one line, we can find the minimum in a list using the max (), function and then determine the index of the maximum element using the built-in index () function in python.

Note:
index () returns the index of the first occurrence if the element appears multiple times. Thus, if the maximum (or minimum) occurs more than once, the first occurrence is returned.

The above approach is implemented below:

 # function for finding the minimum and maximum position in the list def minimum (a, n):   # built-in function to find the minimum position minpos = a.index ( min (a))   # built-in function to find the maximum position maxpos = a.index ( max (a))    # print position print "The maximum is at position" , maxpos + 1   print "The minimum is at position" , minpos + 1     # driver code a = [ 3 , 4 , 1 , 3 , 4 , 5 ]  minimum ( a, len (a))

Output:

The maximum is at position 6 The minimum is at position 3