Как найти номер максимального элемента массива python

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

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

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

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

  1. Get Index of the Maximum Value of a List With the max() and list.index() Functions in Python
  2. Get Index of the Minimum Value of a List With the min() and list.index() Functions in Python
  3. Get Index of the Maximum Value of a List With the numpy.argmax() Function in Python
  4. Get Index of the Minimum Value of a List With the numpy.argmin() Function in Python

Get Index of Maximum and Minimum Value of a List in Python

In this tutorial, we will discuss methods to get the index of the maximum and minimum values of a list in Python.

Get Index of the Maximum Value of a List With the max() and list.index() Functions in Python

The max() function gives the maximum value in a list in Python. The list.index(x) method gives the index of x in the list. The following code example shows us how we can get the index of the maximum value of a list with the max() and list.index() functions in Python.

list1 = [10, 12, 13, 0, 14]

tmp = max(list1)
index = list1.index(tmp)

print(index)

Output:

In the above code, we first get the maximum value inside the list list1 with the max() function and store it in tmp and then get the maximum value’s index by passing tmp to the list1.index() method. The above code can be shortened if we only want to display the index of the maximum value.

list1 = [10, 12, 13, 0, 14]

print(list1.index(max(list1)))

Output:

Get Index of the Minimum Value of a List With the min() and list.index() Functions in Python

The min() function gives the minimum value in a list in Python. The list.index(x) method has already been discussed in the previous section. The following code example shows us how we can get the index of the minimum value of a list with the min() and list.index() functions in Python.

list1 = [10, 12, 13, 0, 14]

tmp = min(list1)
index = list1.index(tmp)

print(index)

Output:

In the above code, we first get the smallest value inside the list list1 with the min() function and store it in tmp. And then we get the minimum value’s index by passing tmp to the list1.index() function. The above code can be shortened if we only want to display the index of the minimum value.

list1 = [10, 12, 13, 0, 14]

print(list1.index(min(list1)))

Output:

Get Index of the Maximum Value of a List With the numpy.argmax() Function in Python

The numpy.argmax() function in the NumPy package gives us the index of the maximum value in the list or array passed as an argument to the function. The following code example shows us how we can get the index of the maximum value of a list with the numpy.argmax() function in Python.

import numpy

list1 = [10, 12, 13, 0, 14]
maxindex = numpy.argmax(list1)

print(maxindex)

Output:

In the above code, we get the index of the maximum value in the list list1 with the numpy.argmax() function.

Get Index of the Minimum Value of a List With the numpy.argmin() Function in Python

The numpy.argmin() function in the NumPy package gives us the index of the minimum value in the list or array passed as an argument to the function. The following code example shows us how we can get the index of the minimum value of a list with the numpy.argmin() function in Python.

import numpy

list1 = [10, 12, 13, 0, 14]
minindex = numpy.argmin(list1)

print(minindex)

Output:

In the above code, we get the index of the minimum value in the list list1 with the numpy.argmin() function.

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

Example:

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

Method 1: Using a native approach

The naive approach will be to traverse in the list and keep 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. Below is the implementation of the naive approach. 

Python3

gfg_list = [8, 1, 7, 10, 5]

min_ele, max_ele = gfg_list[0], gfg_list[0]

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

    if gfg_list[i] < min_ele:

        min_ele = gfg_list[i]

    if gfg_list[i] > max_ele:

        max_ele = gfg_list[i]

print('Minimum Element in the list', gfg_list, 'is', min_ele)

print('Maximum Element in the list', gfg_list, 'is', max_ele)

Output:

Minimum Element in the list [8, 1, 7, 10, 5] is 1
Maximum Element in the list [8, 1, 7, 10, 5] is 10

Time Complexity: O(n)
Auxiliary Space: O(n), where n is length of given list.

Method 2: Using the inbuilt function

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

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

Python3

def minimum(a, n):

    minpos = a.index(min(a))

    maxpos = a.index(max(a))

    print "The maximum is at position", maxpos + 1

    print "The minimum is at position", minpos + 1

a = [3, 4, 1, 3, 4, 5]

minimum(a, len(a))

Output:

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

Time complexity of these functions is O(n), as they need to iterate over the entire list once. 
Auxiliary Space: This function uses a constant amount of extra space to store the indices of the minimum and maximum values. Therefore, the space complexity of the minimum() function is O(1)

Method 3: Using Pandas

In this method, we will use the idxmin() and idxmax() to print the max index and min index using the Pandas module.

Python3

import pandas as pd

a = [35, 41, 49, 37, 31,

     55, 23, 31, 18, 50,

     32, 37, 28, 27, 24, 35]

print("Min: ", pd.Series(a).idxmin())

print("Max: ", pd.Series(a).idxmax())

Output:

Min:  8
Max:  5

Method 4: Using numpy argmax, argmin

note: install numpy module using command “pip install numpy”

NumPy has argmax and argmin functions which can be used to find the indices of the maximum and minimum element. Here’s how to use these functions to find the maximum and minimum element’s position in a Python list:

Algorithm:

Convert the given list to  NumPy array using numpy.array().
Use argmax() and argmin() functions to find the index of maximum and minimum element in the array.
Print the index of the maximum and minimum element by adding 1 to the index.
 

Python3

import numpy as np

def min_max_position(lst):

    arr = np.array(lst)

    min_pos = np.argmin(arr) + 1

    max_pos = np.argmax(arr) + 1

    print(f"The minimum is at position {min_pos}")

    print(f"The maximum is at position {max_pos}")

lst = [3, 4, 1, 3, 4, 5]

min_max_position(lst)

Output:

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

Time Complexity: O(n), where n is the length of the list. Converting the list to a  array takes O(n) time and finding the indices of the maximum and minimum elements using numpy.argmax() and numpy.argmin() functions also takes O(n) time. Overall time complexity of this method is O(n).

Auxiliary Space: O(n), since we are creating a NumPy array of size n to store the list elements.

Last Updated :
12 Apr, 2023

Like Article

Save Article

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