Find max in list Python

Short answer: To find the maximal list in a list of lists, you need to make two lists comparable. How? With the key argument of the max() function. The key argument is a function that takes one input (a list) and returns one output (a numerical value). The list with the largest numerical value is returned as the maximum of the list of lists.

Problem: Say you have a list of lists (nested list) and you want to find the maximum of this list. It’s not trivial to compare lists—what’s the maximum among lists after all? To define the maximum among the inner lists, you may want to consider different objectives.

  1. The first element of each inner list.
  2. The i-th element of each inner list.
  3. The sum of inner list elements.
  4. The maximum of inner list elements.
  5. The minimum of inner list elements.
Find max in list Python

Example: Given list of lists [[1, 1, 1], [0, 2, 0], [3, 3, -1]]. Which is the maximum element?

  1. The first element of each inner list. The maximum is [3, 3, -1].
  2. The i-th element of each inner list (i = 2). The maximum is [1, 1, 1].
  3. The sum of inner list elements. The maximum is [3, 3, -1].
  4. The maximum of inner list elements. The maximum is [3, 3, -1].
  5. The minimum of inner list elements. The maximum is [3, 3, -1].

So how do you accomplish this?

Solution: Use the max() function with key argument.

Syntax: The max() function is a built-in function in Python (Python versions 2.x and 3.x). Here’s the syntax:

max(iterable, key=None)

Arguments:

ArgumentDescription
iterableThe values among which you want to find the maximum. In our case, it’s a list of lists.
key(Optional. Default None.) Pass a function that takes a single argument and returns a comparable value. The function is then applied to each element in the list. Then, the method find the maximum based on the key function results rather than the elements themselves.

Let’s study the solution code for our different versions of calculating the maximum “list” of a list of lists (nested list).

lst = [[1, 1, 1], [0, 2, 0], [3, 3, -1]] # Maximum using first element print(max(lst, key=lambda x: x[0])) # [3, 3, -1] # Maximum using third element print(max(lst, key=lambda x: x[2])) # [1, 1, 1] # Maximum using sum() print(max(lst, key=sum)) # [3, 3, -1] # Maximum using max print(max(lst, key=max)) # [3, 3, -1] # Maximum using min print(max(lst, key=min)) # [1, 1, 1]

Try it yourself in our interactive code shell:

Related articles:

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Find max in list Python

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

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!