Search code examples
pythonlistfor-loopsum

Index of the highest sum() of sublists


Given a finite list of n sub-lists:

my_list = [[2, 9999], [318, 9999], [990, 9999], [9, 9999], [7767, 9999]]

I want a one-liner concise procedure that returns the index of the sub-list with the highest sum().

If in the event 2 or more sub-lists have an equal sum(), then return the first.

My code:

for ksu in key_set_unique:
   print(sum(ksu))

Solution

  • Since you explicitly asked for a one-liner, here it is:

    >>> list(map(sum, my_list)).index(max(map(sum, my_list)))
    4
    

    This line creates a list of sums using the map function and finds a value in said list using index. The value that is searched for is the max value of the list of sums mentioned earlier.

    Note that this computes the sums of my_list's elements twice, which isn't necessary. Solution without the one-line requirement:

    >>> sum_list = list(map(sum, my_list))
    >>> sum_list.index(max(sum_list))
    4