- Get Index of Max of List in Python
- 1. Quick Examples of Finding Index position of Max Element
- 2. Python Get Index of max() of List
- 2.1 Syntax
- 2.2 Get Index of Max of List Example
- 3. Using for loop & index() to get Max Index
- 3.1 for loop Examples
- 4. Using Series.idxmax() to get Max of Index
- 4.1 Syntax
- 4.2 Example
- 5. Using numpy.array().argmax()
- 5.1 Syntax
- 5.2 Example
- 6. Conclusion
- You may also like reading:
- 5 Ways to Find the list max index in Python
- 1. Finding max index using for loop
- 2. Using built in methods – max() and index()
- 3. Using enumerate() function to find Python list max index
- 4. Finding max index for multiple occurrences of elements
- 5. Maximum index from a numpy array
- Python: как найти индекс максимального значения в списке
- Пример 1: поиск индекса максимального значения в списке
- Пример 2: поиск индекса максимального значения в списке со связями
Get Index of Max of List in Python
How to get the index of the maximum (max) element of the list in Python? If you want to return the maximum element index position from the given list, you can use the max() to get the maximum value and use this value with index() method to get the index position of the maximum element. Apart from this method, we will discuss some other methods that will return the maximum element index position.
Methods to get the index of the max element of list in Python:
- Using max() method
- Using for loop
- Using pandas.Series.idxmax()
- Using numpy.array.argmax()
1. Quick Examples of Finding Index position of Max Element
Following are quick examples of how to get the maximum element index position.
# Quick Examples # Consider the list of integers marks = [82,31,40,78,90,32,120] # Using index() method print("Maximum Index position: ",marks.index(max(marks))) # Using for loop maximum_val= marks[0] for i in range(1, len(marks)): if (marks[i] > maximum_val): maximum_val = marks[i] print("Maximum Index position: ",marks.index(maximum_val)) # Using pandas.Series.idxmax() import pandas as pd print("Maximum Index position: ",pd.Series(marks).idxmax()) # Using numpy.array.argmax() import numpy as np print("Maximum Index position: ",np.array(marks).argmax())
2. Python Get Index of max() of List
We can use the Python max() function to get the maximum element and use the list.index() method to get the index position of the maximum element by passing the maximum element to the index() method.
2.1 Syntax
Let’s look at the syntax of how to use max() with index().
# Syntax mylist1.index(max(mylist1))
Here, mylist1 is the input list.
2.2 Get Index of Max of List Example
Let’s create a list of integers and return the index position of the maximum element. Here, the max(marks) returns the maximum value of the python list, and the index(max(marks)) returns the index position of the maximum value from the list.
# Consider the list of integers marks = [12,31,40,78,90,32] # Using index() method print("Maximum Index position: ",marks.index(max(marks))) # Output: # Maximum Index position: 4
Out of 6 integers, the maximum element is 90 and its index position is 4.
3. Using for loop & index() to get Max Index
Here, we will iterate all elements in the list and compare whether the element is maximum to the current iterating value, If it is maximum, we will store this maximum value in a variable, and finally using the index() method, we will return its index position in the list.
3.1 for loop Examples
Example 1: Let’s create a list of integers and return the index position of the maximum element.
# Consider the list of integers marks = [82,31,40,78,90,32,120] # Using for loop maximum_val= marks[0] for i in range(1, len(marks)): if (marks[i] > maximum_val): maximum_val = marks[i] print("Maximum Value:",maximum_val) print("Maximum Index position: ",marks.index(maximum_val)) # Output: # Maximum Value: 120 # Maximum Index position: 6
Out of 7 integers, the maximum element is 120 and its index position is 6.
Example 2: Let’s create a list of 3 strings and return the index position of the maximum element.
# Consider the list of strings languages = ["punjabi","tamil","malayalam"] maximum_element= languages[0] # Using for loop for i in range(1, len(languages)): if (languages[i] > maximum_element): maximum_element = languages[i] print("Maximum Index position: ",languages.index(maximum_element)) # Output: # Maximum Index position: 1
Among 3 languages, “ tamil ” is maximum (ASCII value of t is greater than the other two elements), So its index position is returned, i.e 1
4. Using Series.idxmax() to get Max of Index
The pandas is a module that is used for data analysis available in python. In this module, a Series is a Data structure that will hold elements in a linear fashion. It will accept idxmax() method which will return the index position of the maximum element present in the Series.
So we will convert our list to a Series by passing our list to the Series and apply idxmax() method to return the index position of maximum value.
4.1 Syntax
Let’s look at the syntax of how to use pandas.Series.idxmax()
# Syntax pd.Series(mylist1).idxmax()
Here, mylist1 is the input list.
4.2 Example
Let’s create a list of integers and return the index position of the maximum element using idxmax().
import pandas as pd # Consider the list of integers marks = [31,40,78,90,32,120] # Using pandas.Series.idxmax() print("Maximum Index position: ",pd.Series(marks).idxmax()) # Output: # MMaximum Index position: 5
Out of 6 integers, the maximum element is 120 and its index position is 5.
5. Using numpy.array().argmax()
The NumPy in python is a module that will perform mathematical operations on arrays. Here, argmax() is a method supported by numpy that will return the index of the maximum element in the numpy array. To use NumPy, you need to install it first and import it.
We can utilize this method by converting our list to the numpy array.
5.1 Syntax
Let’s look at the syntax of how to use numpy.array().argmax()
# Syntax # Here, mylist1 is the input list. np.array(mylist1).argmax()
5.2 Example
Let’s create a list of integers and return the index position of the maximum element using numpy.argmax(). Since NumPy works on arrays, first you need to convert the list to the array by using np.array() funcion.
import numpy as np # Consider the list of integers marks = [91,40,78,90,32,120] # Using numpy.array.argmax() print("Maximum Index position: ",np.array(marks).argmax()) # Output: # Maximum marks Index position: 5
Out of 6 integers, the maximum element is 120 and its index position is 5.
6. Conclusion
In this article, you have learned how to return the maximum (max) value index position from the python list using 4 different approaches. First, we discussed using the for loop & index() and then directly using max() & index(). It can be possible to use idxmax() by converting our list to pandas Series and argmax() by converting our list to the numpy array.
You may also like reading:
5 Ways to Find the list max index in 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 : ')
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:
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 : ')
The output is:
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. 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:
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 : ')
The output is:
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!
Python: как найти индекс максимального значения в списке
Вы можете использовать следующий синтаксис, чтобы найти индекс максимального значения списка в 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 в списке.