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

Let`s take a look at some methods for summing a list and a return list.

Method # 1: Using the Naive Method

# Python code for demo
# sum of the list of list
# using a naive method

 
# Declaring the initial list of the list

L = [[ 1 , 2 , 3 ],

[ 4 , 5 6 ],

  [ 7 , 8 , 9 ]]

 
# Print list of list

print ( "Initial List -" , str (L))

 
# Using the 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)

  
# print result

print ( "final list -" , str (res))

Exit :

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

Method # 2: Using the NumPy Array

# Python code for demonstration
# sum of the list list
# using array functions

import numpy as np

 
# Announcement list start list

List = np. array ([[ 1 , 2 , 3 ],

[ 4 , 5 , 6 ],

[ 7 , 8 , 9 ]])

 
# Print list of list

print ( "Initial List -" , str ( List ))

 
# Using sum

res = np. sum < code class = "plain"> ( List , 0 )

 
# print result

print ( "final list -" , str (res))

Exit:

 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 the list list using
# zip and list comprehension

  
# Declaring initial list of list

List = [[ 1 , 2 , 3 ] ,

[ 4 , 5 , 6 ],

[ 7 , 8 , 9 ]]

 
# Print list of list

print ( "Initial List -" , str ( List ))

 
# Using the comprehension list

res = [ sum (i) for i in zip ( * List )]

  
# print result

print ( "final list -" , str (res))

Exit :

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