Python Maximum sum of elements of list in a list of lists (original) (raw)

Last Updated : 15 Jan, 2025

In this problem, we need to find the maximum sum of elements in a list of lists. A list of lists is a collection of sub-lists and each sub-list contains individual elements. The problem is to find the maximum sum among all the sub-lists. Let's explore various ways to solve this problem.

**Using sum() with max()

The simplest and most efficient way is by using the sum() function to calculate the sum of elements in each sub-list and then using the max() function to find the maximum sum.

Python `

Input list of lists

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

Find the maximum sum of elements in the sub-lists

res = max(sum(sub_lst) for sub_lst in lst) print(res)

`

Explanation:

Let's explore some more ways and see how we can find the maximum sum of elements of list in a list of lists.

Table of Content

**Using for loop

We can also use a for loop to iterate through each sub-list, calculate the sum of each sub-list and then keep track of the maximum sum encountered during the iteration.

Python `

Input list of lists

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

Initialize the maximum sum as a very small number

max_sum = float('-inf')

Loop through each sub-list and calculate the sum

for b in a: cur_sum = sum(b) max_sum = max(max_sum, cur_sum)

print(max_sum)

`

Explanation:

**Using list comprehension and max()

This method is similar to the first one, but we will use list comprehension to create a list of sums and then apply the max() function to find the maximum sum.

Python `

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

Create a list of sums and find the maximum sum

res = max([sum(sub_lst) for sub_lst in a]) print(res)

`

Explanation:

**Using numpy for large lists

If we are working with large lists, the numpy library can provide an efficient solution for this problem. Using numpy's sum() function, we can find the maximum sum of elements in the list of lists.

Python `

import numpy as np a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Convert the list of lists to a numpy array

arr = np.array(a)

Find the maximum sum of elements in a row (sub-list)

res = np.max(np.sum(arr, axis=1)) print(res)

`

Explanation:

Similar Reads