Питон как найти индекс максимального элемента

Given a list of N integers, the task is to write a Python program to find the index of the maximum element in the Python list.

Example:

Input: [  2, 4, 6, 1, 8, 5, 3 ]
Output:  Index of the max element in a list is 4
Explanation: The max element is 8 and its position is 4.

Input: [  10, 1, 5, 3, 8, 9, 7 ]
Output:  Index of the max element in a list is 0
Explanation: The max element is 10 and its position is 0.

Get the index of the max value without using in-built functions

We are given list of integers. Our task is to find the index of the maximum element.

Python3

list1 = 2, 4, 6, 1, 8, 5, 3 ]

ind = 0   

max_element = list1[0]

for i in range (1,len(list1)):

  if list1[i] > max_element:

    max_element = list1[i]

    ind = i

print("Index of the maximum element in the list is: ",ind)

Output

Index of the maximum element in the list is:  4

Time Complexity: O(n),
Auxiliary space: O(1)

Get the index of the max value in the list using the max() and index() 

Here we are given a Python list and our task is to find the index of the maximum element so we are finding the maximum element using max() and then finding the index of that element using index() in Python.

Python3

l = [1, 4, 3, 7, 8, 10, 2]

m = max(l)

print("Index of the max element in a list is", l.index(m))

Output

Index of the max element in a list is 5

Time Complexity: O(n),
Auxiliary space: O(1)

Get the index of the max value in the list using the loop 

Here we are given a list and our task is to find the index of the maximum element so we are finding the maximum element using max() and then finding the index of that element using a while loop and iterating over the list.

Python3

l = [1, 4, 3, 7, 8, 10, 2]

m = max(l)

i = 0

while(i < len(l)):

    if l[i] == m:

        print("Index of the max element in a list is", i)

        break

    i += 1

Output

Index of the max element in a list is 5

Time Complexity: O(n),
Auxiliary space: O(1)

Find the index of the max value in a list  using the enumerate function

Here we are given a list and our task is to find the index of the maximum element so we are iterating over the list using the enumerate() function as the index, pair. If we have the same element at two positions we will return both indexes.

Python3

l = [12, 22, 4, 3, 7, 8, 10, 22]

m = max(l)

for i, j in enumerate(l):

    if j == m:

        print("Index of the max element in a list is", i)

Output

Index of the max element in a list is 1
Index of the max element in a list is 7

Time Complexity: O(n),
Auxiliary space: O(1)

Find the index of the max value in a list using Pandas

Here we are given a list and our task is to find the index of the maximum element so we are finding its index using idxmax() in the Pandas module.

Python3

import pandas as p

l = [12, 4, 3, 7, 8, 10, 22]

print("Index of the max element in a list is", p.Series(l).idxmax())

Output:

Index of the max element in a list is 6

Time Complexity: O(n),
Auxiliary space: O(1)

Find the index of the max value in a list  using Numpy 

Here we are given a list and our task is to find the index of the maximum element so we are finding its index using argmax() in the Numpy module.

Python3

import numpy

l = [12, 4, 3, 7, 8, 10, 22]

idx = numpy.argmax(l)

print("Index of the max element in a list is", idx)

Output:

Index of the max element in a list is 6

Time Complexity: O(n),
Auxiliary space: O(1)

Sort the list in descending order

One new approach that is not discussed in the article is to use the built-in sorted() function to sort the list in descending order, and then access the first element of the sorted list to get the index of the maximum item in the list.

Python3

l = [1, 4, 3, 7, 8, 10, 2]

sorted_list = sorted(l, reverse=True)

max_element = sorted_list[0]

print("Index of the max element in a list is", l.index(max_element))

Output

Index of the max element in a list is 5

Time Complexity: O(nlogn),
Auxiliary space: O(1)

Using Recursion:

We are using recursive method to find the index of maximum element in the list.

Python3

def FindIndex(itr,ind,list1):

  if itr == len(list1):

    print("Index of the maximum element in the list is : ",ind)

    return

  if list1[itr] > list1[ind]:

    ind = itr

  FindIndex(itr+1,ind,list1)

  return

list1 = [2,4,1,9,0,8]

FindIndex(0,0,list1)

Output

Index of the maximum element in the list is :  3

Time Complexity: O(n),
Auxiliary space: O(n)

Last Updated :
11 Apr, 2023

Like Article

Save Article

A list is a data structure in python which is used to store items of multiple data types. Because of that, it is considered to be one of the most versatile data structures. We can store items such as string, integer, float, set, list, etc., inside a given list. A list in python is a mutable data type, which means that even after creating a list its elements can be changed. A list is represented by storing its items inside square brackets ‘[ ]’. We can access list elements using indexing. In this article, we shall be looking into how in a python list, we can find the max index.

1. Finding max index using for loop

Finding the maximum index using a for loop is the most basic approach.

my_list = [10,72,54,25,90,40]
max = my_list[0]
index = 0
for i in range(1,len(my_list)):
  if my_list[i] > max:
    max = my_list[i]
    index = i

print(f'Max index is : {index}')

Here, we have taken a list named ‘my_list’, which contains a list of integers. We initially take the first element of the list as the maximum element and store the element into ‘max’. Then we take a variable as ‘index’ and store it with the value 0.

After that, we shall iterate a loop from index 1 to the last element of the list. Inside the loop using an if statement, we shall compare the ith element, i.e., the current element of ‘my_list’ with the ‘max’ variable. If the value of the current element happens to be greater than the value of ‘max’, then we shall assign the value of the current element to ‘max’ and the current index to ‘i’. After completion of the for loop, we shall print the value of ‘index’, which will denote the index of the maximum value from the list.

The output is:

Max index is : 4

An above method is a naive approach. It is for understanding how the maximum element will be found. There are more compact methods, and now we shall be looking into some of them.

2. Using built in methods – max() and index()

We can use python’s inbuilt methods to find the maximum index out of a python list.

The max() method is used to find the maximum value when a sequence of elements is given. It returns that maximum element as the function output. It accepts the sequence as the function argument.

The index() method is used to find the index of a given element from a python list. It accepts the element as an argument and returns the index of that element. In the case of multiple occurrences, it will return the smallest index of that element.

First, we shall use the max() function to find the maximum element from the given list ‘my_list’ and store it in ‘max_item’. Then using the index() function, we shall pass the ‘max_item’ inside the function. Using my_list.index(), we shall return the index of the maximum element and print that.

my_list = [10,72,54,25,90,40]
max_item = max(my_list)
print(f'Max index is : {my_list.index(max_item)}')

The output is:

Max index is : 4

3. Using enumerate() function to find Python list max index

The enumerate() function in python is used to add a counter to an iterable. With the help of enumerate() function, we can find the index of the maximum elements from a list. We shall use list comprehension for storing the index. List comprehension is a way of creating sequences out of already existing sequences.

my_list = [10,72,54,25,90,40]
max_item = max(my_list)
print([index for index, item in enumerate(my_list) if item == max_item])

Using the max() function, we shall store the value of the maximum element into ‘max_item’. Then, we shall enumerate over my_list and check for which list item the value equals max_item. The index for that element shall be printed as a list item.

The output is:

[4]

4. Finding max index for multiple occurrences of elements

If there are multiple occurrences of the maximum element for a list, then we will have to apply a different logic for the same. We will make use of list comprehension to store multiple indexes inside a list.

my_list = [10,72,90,90,54,25,90,40]
max_item = max(my_list)
index_list = [index for index in range(len(my_list)) if my_list[index] == max_item]
print(index_list)

First, using the max() function, we shall find the maximum element from the list. Then, using list comprehension, we shall iterate over the list ‘my_list’, and whenever the item value equals the ‘max_item’, we shall save that index into ‘my_list’. Then, we shall print the ‘index_list’.

The output is:

[2, 3, 6]

5. Maximum index from a numpy array

To find the maximum item index using the numpy library. First, we shall import the numpy library. Then, using the array() function, we shall pass the list my_list as an argument inside the numpy array. This shall convert the given list into a numpy array and store it into ‘n’. Then, using the argmax() function, we shall print the index of the maximum item from the numpy array.

import numpy as np
my_list = [10,72,54,25,90,40]
n = np.array(my_list)
print(f'Max index is : {np.argmax(n)}')

The output is:

Max index is : 4

That wraps up Python List Max Index. If you have any doubts or any thoughts to share, leave them in the comments below.

Until next time, Keep Learning!

Trending Right Now

  • Efficiently Organize Your Data with Python Trie

  • [Fixed] modulenotfounderror: no module named ‘_bz2

  • [Fixed] Cannot Set verify_mode to cert_none When check_hostname is Enabled

  • Prevent Errors with Python deque Empty Handling

def main():
    a = [2,1,5,234,3,44,7,6,4,5,9,11,12,14,13]
    max = 0
    for number in a:
        if number > max:
            max = number
    print max

if __name__ == '__main__':
    main()

I am able to get the maximum value in the array (without using max() of course…). How can I get the index (position) of that value? Please try to keep it simple without using new Python key words or built-in functions. Thanks!

Levon's user avatar

Levon

137k33 gold badges199 silver badges188 bronze badges

asked Jul 17, 2012 at 21:00

Shankar Kumar's user avatar

Shankar KumarShankar Kumar

2,1776 gold badges25 silver badges31 bronze badges

8

In my code I would use this:

>>> max(enumerate(a),key=lambda x: x[1])[0]
3

answered Jul 17, 2012 at 21:15

ovgolovin's user avatar

2

A simple one liner of:

max( (v, i) for i, v in enumerate(a) )[1]

This avoids having to .index() the list after.

answered Jul 17, 2012 at 21:02

Jon Clements's user avatar

Jon ClementsJon Clements

138k32 gold badges244 silver badges278 bronze badges

1

Update:

max_idx = -1
max_val = a[0]
for i in xrange(1, len(a)):
    if a[i] > max_val:
        max_val = a[i]
        max_idx = i

This doesn’t shadow built-in function max(), and also will give correct answers for lists that consist of only negative values.


Previous solution

a.index(max(a))

will do the trick.

Built-in function max(a) will find the maximum value in your list a, and list function
index(v) will find the index of value v in your list. By combining them, you get what you are looking for, in this case the index value 3.

Note that .index() will find the index of the first item in the list that matches, so if you had several identical “max” values, the index returned would be the one for the first.

For more information:

  • max()
  • index()

In the spirit of “Simple is better than complex.” (Zen of Python)

answered Jul 17, 2012 at 21:01

Levon's user avatar

LevonLevon

137k33 gold badges199 silver badges188 bronze badges

1

If you aren’t allowed to use the built in index() function, just iterate with an index, instead of using a foreach loop.

for i in range(len(a)):
    if a[i] > max:
        max = a[i]
        maxIndex = i

answered Jul 17, 2012 at 21:04

Rob Wagner's user avatar

Rob WagnerRob Wagner

4,39114 silver badges24 bronze badges

9

Use the argmax method of the numpy.array object.

import numpy as np
np.array(a).argmax()

answered Oct 1, 2014 at 14:05

AlexP's user avatar

AlexPAlexP

861 silver badge4 bronze badges

You can use enumerate to also give you an index while iterating through a list:

>>> a = [2, 1, 5, 234, 3, 44, 7, 6, 4, 5, 9, 11, 12, 14, 13]
>>> maxIndex, maxNumber = 0, 0
>>> for index, number in enumerate(a):
        if number > maxNumber:
            maxIndex = index
            maxNumber = number

>>> maxIndex, maxNumber
(3, 234)

answered Jul 17, 2012 at 21:04

poke's user avatar

pokepoke

364k69 gold badges552 silver badges598 bronze badges

Use the index(x) function. See the documentation here http://docs.python.org/tutorial/datastructures.html

def main():
    a = [2,1,5,234,3,44,7,6,4,5,9,11,12,14,13]
    max = 0
    for number in a:
        if number > max:
            max = number
    max_index = a.index(max)
    print max

However, this is not as fast as other suggested answers (e.g. using enumerate). Simple though.

answered Jul 17, 2012 at 21:03

MoRe's user avatar

MoReMoRe

1,47813 silver badges25 bronze badges

this is way simpler

x.index(max(x)) #where x is your list

answered May 16, 2017 at 13:59

Mohamed Emad's user avatar

1

If you like powerfull code you would like this 🙂
If you just have integer numbers you can substitute float by int.

maximum= max(map(float,[2,1,5,234,3,44,7,6,4,5,9,11,12,14,13]))

If you have your input in a text file do this:

file.txt

2 1 5 234 3 44 7 6 4 5 9 11 12 14 13

maximum= max(map(float,(open(‘file.txt’, ‘r’).readline()).split()))

Community's user avatar

answered Apr 1, 2013 at 4:33

Carlos Neves's user avatar

In this tutorial, you’ll learn how to use Python to get the index of the max item in a list. You’ll learn how to find the index of the max item in a Python list, both if duplicates exist and if duplicates don’t exist.

You’ll learn how to do this with for loops, the max() and index() functions, the enumerate() function, and, finally, using the popular data science library, numpy.

Knowing how to work with lists is an important skill for anyone learning Python. Python lists are incredibly common and intuitive data structures in Python. Knowing how to find where the max (or, really, min) values exist in a list is an important skill.

The Quick Answer: Use index()

Quick Answer - Get Index of Max in Python List

Find the Max Value in a Python List

Before we dive into how to find the index of the max value in a list, lets begin by learning how to simply find the max value of an item in a list.

The Python max() function takes one or more iterable objects as its parameters and returns the largest item in that object (official documentation). When we pass in a list, the function returns the maximum value in that list.

Let’s see what this looks like in practice:

# Get Max Value from a List
a_list = [10, 11, 14, 23, 9, 3, 35, 22]

print(max(a_list))

# Returns 35

We can see that when we pass in our list into the Python max() function, that the value 35 is returned.

We’ll be using this function to evaluate against throughout the rest of the tutorial.

In the next section, you’ll learn how to return the index of the maximum value if no duplicates exist or you only need the first item.

Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.

Now that you know how to identify what the max value in a Python list is, we can use this along with the .index() method to find the index of the max value.

One thing to note about this is that this method will return the first instance of the maximum value in that iterable object. If the object contains duplicate items, only the first will be returned. All the other methods shown below will return all of the indices, if duplicates exist.

Let’s see how we can use the .index() method to return the index of the max value:

# Get Index of Max Value from a List
a_list = [10, 11, 14, 23, 9, 3, 35, 22]

max_value = max(a_list)
max_index = a_list.index(max_value)

print(max_index)

# Returns: 6

# You could also write:
# max_index = a_list.index(max(a_list))

What we’ve done here is applied the .index() method to our list a_list. The method takes an argument that indicates what item the method should find. The method will return the first (and, in this case, the only) index position of that value.

In the next section, you’ll learn how to use a Python for-loop to find the index or indices of the max item in a Python list.

Want to learn more about calculating the square root in Python? Check out my tutorial here, which will teach you different ways of calculating the square root, both without Python functions and with the help of functions.

Find Index of Max Item in Python List with a For Loop

In the method above, you learned how to use the Python .index() method to return the first index of the maximum value in a list.

The main limitation of that approach was that it only ever returned the first index it finds. This can be a significant limitation if you know that duplicate values exist in a list. Because of this, this section will teach you how to use a Python for loop to find the indices of the highest value in a Python list.

Let’s see how this works in Python:

# Get Indices of the Max Value from a List using a for loop
a_list = [10, 11, 35, 14, 23, 9, 3, 35, 22]
indices = []

max_value = max(a_list)

for i in range(len(a_list)):
    if a_list[i] == max_value:
        indices.append(i)

print(indices)
# Returns: [2, 7]

What we’ve done here is:

  1. Initialized two lists: our list a_list which contains our values, and an empty list that we’ll use to store the indices.
  2. We created a variable that stores the max value
  3. We then looped over each item in the list to see if it matches the item
  4. If it does, we return its index

In the next section, you’ll learn how to use the incredibly helpful enumerate() function to find the indices of the highest value in a Python list.

Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

Find Index of Max Item in Python List with Enumerate

The Python enumerate() function is an incredible function that lets us iterate over an iterable item, such as a list, and access both the index and the item. This, of course, is very helpful since we’re trying to record the index positions of a given value in a list.

While we could use a for loop for this approach, we will use a list comprehension that allows us to be much more concise in our approach.

Let’s first see what the code looks like and then explore the why and how of it works:

# Get Indices of the Max Value from a List using enumerate()
a_list = [10, 11, 35, 14, 23, 9, 3, 35, 22]
indices = [index for index, item in enumerate(a_list) if item == max(a_list)]

print(indices)
# Returns: [2, 7]

In the code above, we:

  1. Loop over each index and item in our list
  2. If the item is equal to the maximum value of our list, we keep its index
  3. If the item isn’t equal to the highest value, then we do nothing

In the final section of this tutorial, you’ll learn how to use numpy to find the indices of the max item of a list.

Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.

Find Index of Max Item in Python List using numpy

In this final section, you’ll learn how to use numpy in order to find the indices of the items with the highest values in a given Python list.

numpy works well with one of its own data types, arrays, which are list-like structures. One of the benefits of these arrays is that they come with many built-in functions and methods that normal lists do not.

One of these functions is the argmax() function, which allows us to find the first instance of the largest value in the array.

# Get Index of the Max Value from a List using numpy
import numpy as np
a_list = [10, 11, 35, 14, 23, 9, 3, 35, 22]
an_array = np.array(a_list)
index = np.argmax(an_array)

print(index)
# Returns: 2

This works by:

  1. Converting the list to the array
  2. Using the argmax() function returns the index of the first maximum value

Want to learn more about Python f-strings? Check out my in-depth tutorial, which includes a step-by-step video to master Python f-strings!

Conclusion

In this tutorial, you learned how to find the index of the max value of a Python list. You learned how to do this if all values are unique or if duplicates can exist in different lists. You learned how to do this using the index() function, as well as with a for loop. You also learned how to use the enumerate() function in a Python list comprehension, and the popular data science library, numpy.

To learn more about numpy, check out the official documentation here.

  • Редакция Кодкампа

17 авг. 2022 г.
читать 1 мин


Вы можете использовать следующий синтаксис, чтобы найти индекс максимального значения списка в Python:

#find max value in list
max_value = max(list_name)

#find index of max value in list 
max_index = list_name. index (max_value)

В следующих примерах показано, как использовать этот синтаксис на практике.

Пример 1: поиск индекса максимального значения в списке

Следующий код показывает, как найти максимальное значение в списке вместе с индексом максимального значения:

#define list of numbers
x = [9, 3, 22, 7, 15, 16, 8, 8, 5, 2]

#find max value in list
max_value = max(x)

#find index of max value in list
max_index = x. index (max_value)

#display max value
print(max_value)

22

#display index of max value
print(max_index)

2

Максимальное значение в списке равно 22 , и мы видим, что оно расположено в списке со значением индекса 2 .

Примечание. В Python значения индекса начинаются с 0.

Пример 2: поиск индекса максимального значения в списке со связями

В следующем коде показано, как найти максимальное значение в списке вместе с индексом максимального значения, когда имеется несколько максимальных значений.

#define list of numbers with multiple max values
x = [9, 3, 22, 7, 15, 16, 8, 8, 5, 22]

#find max value in list
max_value = max(x)

#find indices of max values in list
indices = [index for index, val in enumerate(x) if val == max_value]

#display max value
print(max_value)

22

#display indices of max value
print(indices)

[2, 9]

Максимальное значение в списке равно 22 , и мы видим, что оно встречается при значениях индекса 2 и 9 в списке.

Дополнительные ресурсы

Как заархивировать два списка в Python
Как преобразовать список в DataFrame в Python
Как построить гистограмму из списка данных в Python

Добавить комментарий