Open In App

Python | Column wise sum of nested list

Last Updated : 17 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a nested list (where sublists are of equal length), write a Python program to find the column-wise sum of the given list and return it in a new list.

Examples:

Input : [[1, 5, 3],
         [2, 7, 8],
         [4, 6, 9]]
Output : [7, 18, 20]

Input : [[20, 5],
         [2, 54],
         [45, 9], 
         [72, 3]]
Output : [139, 71]

Method #1:

Python3




# Python3 program to Column wise sum of nested list
 
def column_sum(lst):
    res=[]
    for i in range(0,len(lst)):
        s=0
        for j in range(0,len(lst[i])):
            s+=lst[j][i]
        res.append(s)
    return res
     
# Driver code
lst = [[1, 5, 3], [2, 7, 8], [4, 6, 9]]
print(column_sum(lst))


Output

[7, 18, 20]

Time Complexity: O(n^2), where n is the length of the longest sublist in the nested list.
Auxiliary Space: O(n), where n is the number of columns in the nested list.

Method #2: zip using list comprehension We can find sum of each column of the given nested list using zip function of python enclosing it within list comprehension. 

Python3




# Python3 program to Column wise sum of nested list
 
def column_sum(lst):
     
     return [sum(i) for i in zip(*lst)]
     
# Driver code
lst = [[1, 5, 3], [2, 7, 8], [4, 6, 9]]
print(column_sum(lst))


Output:

[7, 18, 20]

Time Complexity: O(n) where n is the number of elements in the list 
Auxiliary Space: O(n), where n is the length of the list

Method #3: Using map() method Another approach is to use map(). We apply the sum function to each element in a column and find sum of each column accordingly. 

Python3




# Python3 program to Column wise sum of nested list
 
def column_sum(lst):
     
    return list(map(sum, zip(*lst)))
     
# Driver code
lst = [[1, 5, 3], [2, 7, 8], [4, 6, 9]]
print(column_sum(lst))


Output:

[7, 18, 20]

Time Complexity: O(n), where n is the number of elements in the list
Auxiliary Space: O(n), where n is the number of elements in the list 

 Method #4: Using numpy.sum() numpy.sum() function returns the sum of array elements over the specified axis. 

Python3




# Python3 program to Column wise sum of nested list
from numpy import array
 
def column_sum(lst):
    arr = array(lst)
    return sum(arr, 0).tolist()
     
# Driver code
lst = [[1, 5, 3], [2, 7, 8], [4, 6, 9]]
print(column_sum(lst))


Output:

[7, 18, 20]

Method #5: Using dictionary

Here is another approach using a dictionary to store the sums of each column. This method iterates through each element in the nested list and adds it to the corresponding key in the dictionary.

Python3




def column_sum(lst):
    # Initialize dictionary to store sums
    column_sums = {i: 0 for i in range(len(lst[0]))}
     
    # Iterate through each element in the list
    for sublist in lst:
        for i, val in enumerate(sublist):
            column_sums[i] += val
             
    # Return the values of the dictionary as a list
    return list(column_sums.values())
 
# Test with example input
lst = [[1, 5, 3], [2, 7, 8], [4, 6, 9]]
print(column_sum(lst))
#This code is contributed by Edula Vinay Kumar Reddy


Output

[7, 18, 20]

Time complexity: O(nm), where n is the number of sublists and m is the number of elements in each sublist.
Auxiliary Space: O(m), as we store a sum for each column in the dictionary.



Previous Article
Next Article

Similar Reads

Python Program to Sort the matrix row-wise and column-wise
Given a n x n matrix. The problem is to sort the matrix row-wise and column wise.Examples: Input : mat[][] = { {4, 1, 3}, {9, 6, 8}, {5, 2, 7} } Output : 1 3 4 2 5 7 6 8 9 Input : mat[][] = { {12, 7, 1, 8}, {20, 9, 11, 2}, {15, 4, 5, 13}, {3, 18, 10, 6} } Output : 1 5 8 12 2 6 10 15 3 7 11 18 4 9 13 20 Approach: Following are the steps: Sort each r
4 min read
Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix
Find the number of negative numbers in a column-wise / row-wise sorted matrix M[][]. Suppose M has n rows and m columns. Example: Input: M = [-3, -2, -1, 1] [-2, 2, 3, 4] [4, 5, 7, 8] Output : 4 We have 4 negative numbers in this matrix We strongly recommend you to minimize your browser and try this yourself first. Naive Solution: Here's a naive, n
15+ min read
Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Python - Column-wise elements in Dictionary value list
Given dictionary with value list, extract elements columnwise. Input : test_dict = {'Gfg' : [3, 6], 'is' : [4, 2], 'best' :[9, 1]} Output : [3, 4, 9, 6, 2, 1] Explanation : 3, 4, 9 from col1 and then 6, 2, 1 from 2 are extracted in order. Input : test_dict = {'Gfg' : [3], 'is' : [4], 'best' :[9]} Output : [3, 4, 9] Explanation : 3, 4, 9 from col1 i
3 min read
heapq in Python to print all elements in sorted order from row and column wise sorted matrix
Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of matrix in sorted order. Examples: Input : mat= [[10, 20, 30, 40], [15, 25, 35, 45], [27, 29, 37, 48], [32, 33, 39, 50]] Output : Elements of matrix in sorted order [10, 15, 20, 25, 27, 29, 30, 32, 33, 35, 37, 39, 40, 45, 48, 50] This problem h
2 min read
Python | Cumulative Nested Tuple Column Product
Sometimes, while working with records, we can have a problem in which we require to perform index wise multiplication of tuple elements. This can get complicated with tuple elements to be tuple and inner elements again be tuple. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using zip() + nested generator expression The
7 min read
How to add column sum as new column in PySpark dataframe ?
In this article, we are going to see how to perform the addition of New columns in Pyspark dataframe by various methods. It means that we want to create a new column that will contain the sum of all values present in the given row. Now let's discuss the various methods how we add sum as new columns But first, let's create Dataframe for Demonstratio
4 min read
How to add a column to a nested struct in a pyspark
In this article, we are going to learn how to add a column to a nested struct using Pyspark in Python. Have you ever worked in a Pyspark data frame? If yes, then might surely know how to add a column in Pyspark, but do you know that you can also create a struct in Pyspark? The struct is used to programmatically specify the schema to the DataFrame a
4 min read
Python | Pair and combine nested list to tuple list
Sometimes we need to convert between the data types, primarily due to the reason of feeding them to some function or output. This article solves a very particular problem of pairing like indices in list of lists and then construction of list of tuples of those pairs. Let's discuss how to achieve the solution of this problem. Method #1 : Using zip()
10 min read
Python | Find maximum length sub-list in a nested list
Given a list of lists, write a Python program to find the list with maximum length. The output should be in the form (list, list_length). Examples: Input : [['A'], ['A', 'B'], ['A', 'B', 'C']] Output : (['A', 'B', 'C'], 3) Input : [[1, 2, 3, 9, 4], [5], [3, 8], [2]] Output : ([1, 2, 3, 9, 4], 5) Let's discuss different approaches to solve this prob
3 min read
Practice Tags :
three90RightbarBannerImg