Python | Maximum and minimum element’s position in a list

Given a list of N integers, find the maximum and minimum element’s position in the list.

Examples:

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

The naive approach will be to traverse in the list and keep a track of the minimum and maximum along with their indices. We have to do N comparisons for minimum and at the same time N comparisons for maximum.

Python inbuilt function allows us to find it in one line, we can find the minimum in the list using the min() function and then us index() function to find out the index of that minimum element. Similarly we can do the same for finding out the maximum element using max() function and then find out the index of the maximum element using index() inbuilt function in python.

Note :
index() returns index of first occurrence in case there are multiple occurrences of an element. So if maximum(or minimum) occurs more than once, first occurrence is returned.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

# function to find minimum and maximum position in list
def minimum(a, n):
  
    # inbuilt function to find the position of minimum 
    minpos = a.index(min(a))
      
    # inbuilt function to find the position of maximum 
    maxpos = a.index(max(a)) 
      
    # printing the 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))

chevron_right


Output:

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


My Personal Notes arrow_drop_up

Striver(underscore)79 at Codechef and codeforces D

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Akanksha_Rai