Find the Max value in a list of lists in Python

avatar

Borislav Hadzhiev

Last updated: Sep 15, 2022

banner

Photo from Unsplash

Find the Max value in a list of lists in Python #

To find the max value in a list of lists:

  1. Use the max() function.
  2. Pass the key argument to the functions.
  3. Select the element in the sublist to be compared.
  4. The max() function will return the max value in the list.
main.py
list_of_lists = [[1, 'bobby', 5], [2, 'hadz', 4], [3, 'com', 1]] max_list = max(list_of_lists, key=lambda sublist: sublist[0]) print(max_list) # 👉️ [3, 'com', 1] max_value = max(sublist[0] for sublist in list_of_lists) print(max_value) # 👉️ 3

We used the max() function to get the max value in a list of lists.

The max function returns the largest item in an iterable or the largest of two or more arguments.

The max function also takes an optional key argument.

The key argument specifies a one-argument ordering function.

main.py
list_of_lists = [[1, 'bobby', 5], [2, 'hadz', 4], [3, 'com', 1]] max_list = max(list_of_lists, key=lambda sublist: sublist[0]) print(max_list) # 👉️ [3, 'com', 1]

You can imagine that:

  1. The lambda function gets called for each sublist in the list.
  2. The function returns the Nth element of each sublist.
  3. The max() function returns the sublist with the max Nth element.

We compared the first item in each list in the example, but you can compare the items at any other index.

main.py
list_of_lists = [[1, 'bobby', 5], [2, 'hadz', 4], [3, 'com', 1]] max_list = max(list_of_lists, key=lambda sublist: sublist[2]) print(max_list) # 👉️ [1, 'bobby', 5] max_value = max(sublist[2] for sublist in list_of_lists) print(max_value) # 👉️ 5
Python indexes are zero-based, so the first item in a list has an index of 0, and the last item has an index of -1 or len(my_list) - 1.

If you need to get the max value in a list of lists, instead of getting the sublist that contains the max value, use a generator expression.

main.py
list_of_lists = [[1, 'bobby', 5], [2, 'hadz', 4], [3, 'com', 1]] max_value = max(sublist[0] for sublist in list_of_lists) print(max_value) # 👉️ 3 max_value = max(sublist[2] for sublist in list_of_lists) print(max_value) # 👉️ 5

We used a generator expression to iterate over the list of lists.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we access an item at a specific index in each sublist and return the result.

The max() function gets called with a generator object of integers and returns the max value.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.