Как найти индекс максимального числа в питоне
Перейти к содержимому

Как найти индекс максимального числа в питоне

  • автор:

 

Python: Get Index of Max Item in List

Python Get Index of Max Item in List Cover Image

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

Table of Contents

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:

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.

Find Index of Max Item in Python List using index

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:

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:

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:

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.

  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 .

 

5 Ways to Find the list max index in Python

python list max index

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.

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.

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.

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.

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.

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.

Как найти индекс максимального числа в питоне

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

Example:

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

Output:

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:

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.

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.

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.

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.

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.

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.

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

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

 

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

Ваш адрес email не будет опубликован. Обязательные поля помечены *