Search code examples
pythonlistsummax

How to find the list in a list of lists whose sum of elements is the greatest?


I have a list of lists:

x = [[1,2,3], [4,5,6], [7,8,9], [2,2,0]]

I want to get the list whose sum of its elements is the greatest in the list. In this case [7,8,9].

I'd rather have a fancy map or lambda or list comprehension method than a for/while/if loop.

Best Regards


Solution

  • max takes a key argument, with it you can tell max how to calculate the value for each item in an iterable. sum will do nicely here:

    max(x, key=sum)
    

    Demo:

    >>> x = [[1,2,3], [4,5,6], [7,8,9], [2,2,0]]
    >>> max(x, key=sum)
    [7, 8, 9]
    

    If you need to use a different method of summing your items, you can specify your own functions too; this is not limited to the python built-in functions:

    >>> def mymaxfunction(item):
    ...     return sum(map(int, item))
    ...
    >>> max([['1', '2', '3'], ['7', '8', '9']], key=mymaxfunction)
    ['7', '8', '9']