Python | Positions of maximum element in list

Sometimes, while working with Python lists, we can have a problem in which we intend to find the position of maximum element of list. This task is easy and discussed many times. But sometimes, we can have multiple maximum elements and hence multiple maximum positions. Let’s discuss a shorthand to achieve this task in this case.

Method : Using max() + enumerate() + list comprehension
In this method, the combination of above functions is used to perform this particular task. This is performed in two steps. In 1st, we acquire the maximum element and then access the list using list comprehension and corresponding element using enumerate and extract every element position equal to maximum element processed in step 1.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Positions of maximum element in list
# Using list comprehension + max() + enumerate()
  
# initializing list
test_list = [8, 4, 6, 8, 2, 8]
  
# printing list
print("The original list : " + str(test_list))
  
# Positions of maximum element in list
# Using list comprehension + max() + enumerate()
temp = max(test_list)
res = [i for i, j in enumerate(test_list) if j == temp]
  
# Printing result
print("The Positions of maximum element : " + str(res))

chevron_right


Output :

 
The original list : [8, 4, 6, 8, 2, 8]
The Positions of maximum element : [0, 3, 5]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.