Open In App

Python | Ways to sum list of lists and return sum list

The list is an important container and is used almost in every code of day-day programming as well as web development, more it is used, the more is the requirement to master it and hence knowledge of its operations is necessary. Given a list of lists, the program to suppose to return the sum as the final list. Let’s see some of the methods to sum a list of list and return list.

Method # 1: Using Naive method




# Python code to demonstrate
# sum of list of list
# using naive method
 
# Declaring initial list of list
L = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]
 
# Printing list of list
print("Initial List - ", str(L))
 
# Using naive method
res = list()
for j in range(0, len(L[0])):
    tmp = 0
    for i in range(0, len(L)):
        tmp = tmp + L[i][j]
    res.append(tmp)
 
# Printing result
print("final list - ", str(res))

Output:
Initial List -  [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
final list -  [12, 15, 18]

Time complexity: O(n^2), where n is the length of the outer list.
Auxiliary Space: O(n), the space required to store the result list.

Method #2: Using numpy array 

A numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays.




# Python code to demonstrate
# sum of list of list
# using numpy array functions
 
import numpy as np
 
# Declaring initial list of list
List = np.array([[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]])
 
# Printing list of list
print("Initial List - ", str(List))
 
# Using numpy sum
res = np.sum(List, 0)
 
# printing result
print("final list - ", str(res))

Output:
Initial List -  [[1 2 3]
                 [4 5 6]
                 [7 8 9]]
final list -  [12 15 18]

Method #3: Using zip() and list comprehension




# Python code to demonstrate
# sum of list of list using
# zip and list comprehension
 
# Declaring initial list of list
List = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]
 
# Printing list of list
print("Initial List - ", str(List))
 
# Using list comprehension
res = [sum(i) for i in zip(*List)]
 
# Printing result
print("final list - ", str(res))

Output:
Initial List -  [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
final list -  [12, 15, 18]

Time Complexity: O(n), where n is the length of List.
Auxiliary Space: O(n), where n is the length of ‘res’ list.

Method #4: Using map() and lambda

One approach that is not present in the article is using the map function and a lambda function to sum the elements of the list of lists.

The map function applies a given function to each element of an iterable (such as a list) and returns a new iterable with the modified elements. In this case, we can use a lambda function that takes a list as an argument and returns the sum of its elements, and apply it to each sublist in the list of lists using map.

Here is an example of how you could use this approach to sum the list of lists:




lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
 
sum_lst = list(map(lambda *x: sum(x), *lst))
print(sum_lst)  # [12, 15, 18]
 
# This code is contributed by Edula Vinay Kumar Reddy

Output
[12, 15, 18]

The time complexity of the code provided is O(n * m), where n is the number of sublists and m is the length of each sublist. This is because the map function needs to iterate over all n sublists and m elements in each sublist. The space complexity is also O(m).

Method #5: Using itertools

Approach:

  1. Import the itertools module: import itertools
  2. Define the sum_lists_itertools function with lst as the parameter:
  3. Use the zip_longest() function from itertools to transpose the list of lists. This function takes the asterisk * operator to unpack the sub-lists and fill any missing values with a fillvalue of 0.
  4. Use a list comprehension to sum the corresponding elements of each sub-list and return the resulting list:
  5. Define the input ‘lst’ with a list of lists.
  6. Call the sum_lists_itertools function with ‘lst’ as an argument and assign the result to result.
  7. Print the result to the console.




import itertools
 
def sum_lists_itertools(lst):
    transposed = itertools.zip_longest(*lst, fillvalue=0)
    return [sum(x) for x in transposed]
 
lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = sum_lists_itertools(lst)
print(result)

Output
[12, 15, 18]

Time Complexity: O(N^2)
Auxiliary Space: O(N)

Method #6: Using built-in function reduce() from the functools module




from functools import reduce
 
# Declaring initial list of list
List = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]
 
# Printing list of list
print("Initial List - ", str(List))
 
# Using reduce() and lambda function
res = reduce(lambda x, y: [x[i]+y[i] for i in range(len(x))], List)
 
# printing result
print("Final list - ", str(res))

Output
('Initial List - ', '[[1, 2, 3], [4, 5, 6], [7, 8, 9]]')
('Final list - ', '[12, 15, 18]')

Time Complexity: O(N^2)
Auxiliary Space: O(N)


Article Tags :