Max in list of lists python

Given a list of lists, write a Python program to find the list with maximum length. The output should be in the form (list, list_length).

Examples:



Input : [['A'], ['A', 'B'], ['A', 'B', 'C']] Output : (['A', 'B', 'C'], 3) Input : [[1, 2, 3, 9, 4], [5], [3, 8], [2]] Output : ([1, 2, 3, 9, 4], 5)

 
Let’s discuss different approaches to solve this problem.

Approach #1 : Using for loop (Naive)
This is a brute force method in which we iterate through each list item(list) and find the list with maximum length. Similarly, we use the for loop to find length of each list and output the maximum length.

def FindMaxLength(lst):

    maxList = max((x) for x in lst)

    maxLength = max(len(x) for x in lst )

    return maxList, maxLength

lst = [['A'], ['A', 'B'], ['A', 'B', 'C']]

print(FindMaxLength(lst))

Output: (['A', 'B', 'C'], 3)

 
Approach #2 : Using map
In this method we use Python map function to iterate over the inner lists to create a list of lengths, then get the maximum with max function.

def FindMaxLength(lst):

    maxList = max(lst, key = len)

    maxLength = max(map(len, lst))

    return maxList, maxLength

lst = [['A'], ['A', 'B'], ['A', 'B', 'C'], ]

print(FindMaxLength(lst))

Output: (['A', 'B', 'C'], 3)

 
Approach #3 : Using lambda operator
One more method in Python to find the longest length list is the lambda operator. It is used for creating small, one-time and anonymous function objects in Python. Here we pass a variable i as argument in the len(i) expression and find the maximum length.

def FindMaxLength(lst):

    maxList = max(lst, key = lambda i: len(i))

    maxLength = len(maxList)

    return maxList, maxLength

lst = [['A'], ['A', 'B'], ['A', 'B', 'C']]

print(FindMaxLength(lst))

Output: (['A', 'B', 'C'], 3)


Article Tags :

Practice Tags :

This tutorial will demonstrate how to find the maximum value in a list in Python.

A few scenarios and data types will be covered, from a simple integer list to a more complex structure such as an array within an array.

Use the for Loop to Find Max Value in a List in Python

The Python for loop can be used to find the max value in a list by comparing each value in the array and storing the largest value in a variable.

For example, let’s declare an array of random integers and print out the max value. Also, declare a variable max_value to store the maximum value and print it out after the loop is finished.

numbers = [55, 4, 92, 1, 104, 64, 73, 99, 20] max_value = None for num in numbers: if (max_value is None or num > max_value): max_value = num print('Maximum value:', max_value)

Output:

Maximum value: 104

If the index of the maximum value is needed to further manipulate the output, simply use the Python function enumerate, which enables the for loop to accept a second argument indicating the index of the current iteration of the loop.

Add a new variable, max_idx, to store the max index of the maximum value.

numbers = [55, 4, 92, 1, 104, 64, 73, 99, 20] max_value = None max_idx = None for idx, num in enumerate(numbers): if (max_value is None or num > max_value): max_value = num max_idx = idx print('Maximum value:', max_value, "At index: ", max_idx)

Output:

Maximum value: 104 At index: 4

Use the max() Function to Find Max Value in a List in Python

Python has a pre-defined function called max() that returns the maximum value in a list.

Finding the maximum value using max() will only need a single line.

numbers = [55, 4, 92, 1, 104, 64, 73, 99, 20] max_value = max(numbers) print('Maximum value:', max_value)

Output:

Maximum value: 104

If you need the index of the maximum value, we can call the built-in index() function in a Python list. The function will return the index of the specified element within the array.

numbers = [55, 4, 92, 1, 104, 64, 73, 99, 20] max_value = max(numbers) print('Maximum value:', max_value, "At index:", arr.index(max_value))

Output:

Maximum value: 104 At index: 4

Use max() to Find Max Value in a List of Strings and Dictionaries

The function max() also provides support for a list of strings and dictionary data types in Python.

The function max() will return the largest element, ordered by alphabet, for a list of strings. The letter Z is the largest value, and A is the smallest.

strings = ['Elephant', 'Kiwi', 'Gorilla', 'Jaguar', 'Kangaroo', 'Cat'] max_value = max(strings) print('Maximum value:', max_value, "At index:", strings.index(max_value))

Output:

Maximum value: Kiwi At index: 1

Find Max Value in a Nested List in Python

A more complicated example is to find the maximum value of a nested list in Python.

First, let’s declare random values in a nested list.

nst = [ [1001, 0.0009], [1005, 0.07682], [1201, 0.57894], [1677, 0.0977] ]

From this nested list, we want to get the maximum value of the 2nd element. We also want to print out the 1st element and treat it as an index. The nested list is treated more like a key-value pair within a list.

To find the maximum value of this complex structure, we can use the function max() with its optional argument key, which takes note of the element within the nested list to compare.

nst = [ [1001, 0.0009], [1005, 0.07682], [1201, 0.57894], [1677, 0.0977] ] idx, max_value= max(nst, key=lambda item: item[1]) print('Maximum value:', max_value, "At index:",idx)

The key argument accepts a lambda function and will allow the function max() to return a key-value pair.

Output:

Maximum value: 0.57894 At index: 1201

In summary, this tutorial covered different methods of finding the max values within different types of lists in Python. You can read more about the function max() and its different arguments here. Aside from max() there are built-in functions like min(), all(), and any() that manipulate iterables in Python.

DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python List

  • Convert a Dictionary to a List in Python
  • Remove All the Occurrences of an Element From a List in Python
  • Remove Duplicates From List in Python
  • Get the Average of a List in Python
  • Let’s talk about using Python’s min and max functions on a list containing other lists. Sometimes this is referred to as a nested list or a lists of lists.

    Max in list of lists python

    Finding the minimum or maximum element of a list of lists1 based on a specific property of the inner lists is a common situation that can be challenging for someone new to Python.

    To give us a more concrete example to work with, let’s say we have the following list of item, weight pairs2:

    nested_list = [['cherry', 7], ['apple', 100], ['anaconda', 1360]]

    We want Python to select the minimum and maximum element based on each item’s weight stored at index 1. We expect min and max to return the following elements:

    • min(nested_list) should be ['cherry', 7]
    • max(nested_list) should be ['anaconda', 1360]

    But if we simply call min and max on that nested list we don’t get the results we expected.

    The ordering we get seems to be based on the item’s name, stored at index 0:

    >>> min(nested_list) ['anaconda', 1360] # Not what we expected! >>> max(nested_list) ['cherry', 7] # Not what we expected!

    Let’s stop for a moment to think about how Python’s max function works internally. The algorithm looks something like this:

    def my_max(sequence): """Return the maximum element of a sequence""" if not sequence: raise ValueError('empty sequence') maximum = sequence[0] for item in sequence: if item > maximum: maximum = item return maximum

    The interesting bit of behavior here can be found in the condition that selects a new maximum: if item > maximum:.

    This condition works nicely if sequence only contains primitive types like int or float because comparing those is straightforward (in the sense that it’ll give an answer that we intuitively expect; like 3 > 2).

    However, if sequence contains other sequences then things get a little more complex. Let’s look at the Python docs to learn how Python compares sequences:

    Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.

    When max needs to compare two sequences to find the “larger” element then Python’s default comparison behavior might not be what we want3.

    Now that we understand why we get an unexpected result we can think about ways to fix our code.

    We need to tell max to compare the items differently.

    In our example, Python’s max looks at the first item in each inner list (the string cherry, apple, or anaconda) and compares it with the current maximum element. That’s why it returns cherry as the maximum element if we just call max(nested_list).

    How do we tell max to compare the second item of each inner list?

    Let’s imagine we had an updated version of my_max called my_max_by_weight that uses the second element of each inner list for comparison:

    def my_max_by_weight(sequence): if not sequence: raise ValueError('empty sequence') maximum = sequence[0] for item in sequence: # Compare elements by their weight stored # in their second element. if item[1] > maximum[1]: maximum = item return maximum

    That would do the trick! We can see that my_max_by_weight selects the maximum element we expected:

    >>> my_max_by_weight(nested_list) ['anaconda', 1360]

    Now imagine we needed to find the maximum of different kinds of lists.

    Perhaps the index (or key) we’re interested in won’t always be the second item. Maybe sometimes it’ll be the third or fourth item, or a different kind of lookup is necessary all together.

    Wouldn’t it be great if we could reuse the bulk of the code in our implementation of my_max? Some parts of it will always work the same, for example checking if an empty sequence was passed to the function.

    Because Python allows us to treat functions as data we can extract the code selecting the comparison key into its own function. We’ll call that the key func. We can write different kinds of key funcs and pass them to my_max as necessary.

    This gives us complete flexibility! Instead of just being able to choose a specific list index for the comparison, like index 1 or 2, we can tell our function to select something else entirely – for example, the length of the item’s name.

    Let’s have a look at some code that implements this idea:

    def identity(x): return x def my_max(sequence, key_func=None): """ Return the maximum element of a sequence. key_func is an optional one-argument ordering function. """ if not sequence: raise ValueError('empty sequence') if not key_func: key_func = identity maximum = sequence[0] for item in sequence: # Ask the key func which property to compare if key_func(item) > key_func(maximum): maximum = item return maximum

    In the code example you can see how by default we let my_max use a key func we called identity, which just uses the whole, unmodified item to do the comparison.

    With identity as the key func we expect my_max to behave the same way max behaves.

    nested_list = [['cherry', 7], ['apple', 100], ['anaconda', 1360]] >>> my_max(nested_list) ['cherry', 7]

    And we can confirm that we’re still getting the same (incorrect) result as before, which is a pretty good indication that we didn’t screw up the implementation completely 😃.

    Now comes the cool part – we’re going to override the comparison behavior by writing a key_func that returns the second sub-element instead of the element itself4:

    def weight(x): return x[1] >>> my_max(nested_list, key_func=weight) ['anaconda', 1360]

    And voilà, this is the maximum element we expected to get!

    Just to demonstrate the amount of flexibility this refactoring gave us, here’s a key_func that selects the maximum element based on the length of the item’s name:

    def name_length(x): return len(x[0]) >>> my_max(nested_list, key_func=name_length) ['anaconda', 1360]

    Instead of defining the key func explicitly with def and giving it a name we can also use Python’s lambda keyword to define a function anonymously. This shortens the code quite a bit (and won’t create a named function):

    my_max(nested_list, key_func=lambda x: x[1]) >>> ['anaconda', 1360]

    To make the naming a little slicker (albeit less expressive) imagine we’ll shorten the key_func arg to key and we’ve arrived at a code snippet that works with the max function in vanilla Python.

    This means we’ll no longer need our own re-implementation of Python’s max function to find the “correct” maximum element:

    # This is pure, vanilla Python: >>> max(nested_list, key=lambda x: x[1]) ['anaconda', 1360]

    The same also works for Python’s built-in min:

    >>> min(nested_list, key=lambda x: x[1]) ['cherry', 7]

    It even works for Python’s sorted function, making the “key func” concept really valuable in a number of situations you might face as a Python developer:

    >>> sorted(nested_list, key=lambda x: x[1]) [['cherry', 7], ['apple', 100], ['anaconda', 1360]]

    I hope this post helped you out. What started out as a simple question ended up being a little more involved than you may have expected. But it’s often like that when you learn about new programming concepts.

    Feel free to drop me a line of Twitter or over email if you got stuck anywhere. I’d love to improve this tutorial over time :)