Python | Column summation in uneven sized lists
Last Updated :
02 May, 2023
The usual list of list, unlike conventional C type Matrix, can allow the nested list of lists with variable lengths, and when we require the summation of its columns, the uneven length of rows may lead to some elements in that element to be absent and if not handled correctly, may throw exception. Let's discuss certain ways in which this problem can be performed in error-free manner.
Method #1 : Using sum() + filter() + map() + list comprehension The combination of above three function combined with list comprehension can help us perform this particular task, the sum function helps to perform the summation, filter allows us to check for the present elements and all rows are combined using the map function. Works only with python 2
Python3
# Python code to demonstrate
# Column summation in uneven sized lists
# using sum() + filter() + map() + list comprehension
# initializing list of lists
test_list = [[1, 5, 3], [4], [9, 8]]
# printing original list
print ("The original list is : " + str(test_list))
# using sum() + filter() + map() + list comprehension
# Column summation in uneven sized lists
res = [sum(filter(None, j)) for j in map(None, *test_list)]
# printing result
print ("The summation of columns is : " + str(res))
Output : The original list is : [[1, 5, 3], [4], [9, 8]]
The summation of columns is : [14, 13, 3]
Time Complexity: O(n*n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2 : Using list comprehension + sum() + zip_longest() If one desires not to play with the None values, one can opt for this method to resolve this particular problem. The zip_longest function helps to fill the not present column with 0 so that it does not has to handle the void of elements not present.
Python3
# Python3 code to demonstrate
# Column summation in uneven sized lists
# using list comprehension + sum() + zip_longest()
import itertools
# initializing list of lists
test_list = [[1, 5, 3], [4], [9, 8]]
# printing original list
print ("The original list is : " + str(test_list))
# using list comprehension + sum() + zip_longest()
# Column summation in uneven sized lists
res = [sum(i) for i in itertools.zip_longest(*test_list, fillvalue = 0)]
# printing result
print ("The summation of columns is : " + str(res))
Output : The original list is : [[1, 5, 3], [4], [9, 8]]
The summation of columns is : [14, 13, 3]
Method #3 : Using max
To perform column summation in uneven sized lists in Python, you can use the built-in zip() function to group the elements of each sub-list by their corresponding positions, and then use a list comprehension to sum the elements in each group.
Python3
original_list = [[1, 5, 3], [4], [9, 8]]
# Determine the maximum length of the sub-lists
max_length = max(len(sub_list) for sub_list in original_list)
# Initialize the output list with zeros
column_sums = [0] * max_length
# Iterate through the columns of the sub-lists and add the values to the output list
for sub_list in original_list:
for i in range(len(sub_list)):
column_sums[i] += sub_list[i]
# Print the original list and the column sums
print("The original list is :", original_list)
print("The summation of columns is :", column_sums)
OutputThe original list is : [[1, 5, 3], [4], [9, 8]]
The summation of columns is : [14, 13, 3]
Time complexity: O(M*N)
Auxiliary Space: O(M)
Method #4 : Using reduce() and zip_longest():
Algorithm:
1.Initialize the list of lists.
2.Use itertools.zip_longest() to make lists equal in size by adding 0s to fill the missing values.
3.Use list comprehension to sum the columns.
4.Return the resulting list as the column summation of the uneven sized lists.
Python3
from functools import reduce
import itertools
test_list = [[1, 5, 3], [4], [9, 8]]
# printing original list
print("The original list is:", test_list)
# using reduce() + zip_longest() to get summation of columns
res = list(reduce(lambda x, y: [a+b for a, b in itertools.zip_longest(x, y, fillvalue=0)], test_list))
# printing result
print("The summation of columns is:", res)
#This code is contributed by Jyothi pinjala.
OutputThe original list is: [[1, 5, 3], [4], [9, 8]]
The summation of columns is: [14, 13, 3]
Time complexity: O(n*m) where n is the number of sublists and m is the maximum length of sublists. This is because we are iterating over each element in each sublist to compute the summation.
Space complexity: O(m) where m is the maximum length of sublists. This is because we are creating a new list to store the summation of columns, which has length equal to the maximum length of sublists. Additionally, we are using itertools.zip_longest to iterate over the sublists, which also requires memory proportional to the length of the longest sublist.
METHOD 5:Using .items
APPROACH:
The approach used here is to first create an empty dictionary result to keep track of the column-wise sum. Then for each sublist in the input list, it iterates over the elements in the sublist using the enumerate() function. For each element, it adds the value to the corresponding key in the result dictionary. If the key is not present in the dictionary, it initializes it with a default value of 0. Finally, it sorts the dictionary by key and creates a list of values in the sorted order.
ALGORITHM:
1.Initialize an empty dictionary result.
2.Loop through each sublist in the input list and each element in the sublist:
a. If the dictionary already has a key for the current index, add the element to the value associated with that key.
b. Otherwise, add a new key-value pair to the dictionary with the current index as the key and the element as the value.
3.Convert the dictionary to a list of tuples and sort it by the keys.
4.Extract the values from the sorted list of tuples to get the column sums.
5.Return the column sums.
Python3
def column_sum(lists):
result = {}
for sublist in lists:
for i, val in enumerate(sublist):
result[i] = result.get(i, 0) + val
sorted_result = sorted(result.items())
return [val for key, val in sorted_result]
# Example usage
lists = [[1, 5, 3], [4], [9, 8]]
result = column_sum(lists)
print(result)
Time complexity: The algorithm has a time complexity of O(n * m), where n is the number of sublists in the input list and m is the length of the longest sublist.
Auxiliary Space: The algorithm has a space complexity of O(m), because it creates a dictionary with at most m keys and values.
Approach using numpy:
Note: Install numpy module using command "pip install numpy"
Algorithm:
Initialize a numpy array from the given list of lists.
Calculate the sum of the columns using the sum() function on axis 0.
Convert the resulting numpy array back to a list.
Python3
import numpy as np
# initializing list of lists
test_list = [[1, 5, 3], [4], [9, 8]]
# printing original list
print("The original list is:", test_list)
# converting the list of lists to a numpy array
arr = np.array([np.pad(row, (0, len(max(test_list, key=len)) - len(row)), 'constant') for row in test_list])
# calculating the sum of columns using numpy sum() function
res = np.sum(arr, axis=0).tolist()
# printing the resulting list
print("The summation of columns is:", res)
Output:
The original list is: [[1, 5, 3], [4], [9, 8]]
The summation of columns is: [14, 13, 3]
Time complexity: O(n^2) for creating the numpy array, where n is the length of the longest sub-list in the given list of lists.
Auxiliary Space: O(n^2) for the numpy array created, where n is the length of the longest sub-list in the given list of lists.
Similar Reads
Python | Summation of Kth Column of Tuple List
Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the possible accumulation of its Kth index. This problem has applications in the web development domain while working with data information. Let's discuss certain ways in which this task ca
7 min read
Python - Uneven Sized Matrix Column Minimum
The usual list of list, unlike conventional C type Matrix, can allow the nested list of lists with variable lengths, and when we require the minimum of its columns, the uneven length of rows may lead to some elements in that elements to be absent and if not handled correctly, may throw exception. Le
7 min read
Python | Uneven Sized Matrix Column product
The usual list of list, unlike conventional C type Matrix, can allow the nested list of lists with variable lengths, and when we require the product of its columns, the uneven length of rows may lead to some elements in that elements to be absent and if not handled correctly, may throw exception. Le
7 min read
Python | Column summation of tuples
Sometimes, we encounter a problem where we deal with a complex type of matrix column summation in which we are given a tuple and we need to perform the summation of its like elements. This has a good application in Machine Learning domain. Let's discuss certain ways in which this can be done. Method
7 min read
Python - Index Value Summation List
To access the elements of lists, there are various methods. But sometimes we may require to access the element along with the index on which it is found and compute its summation, and for that, we may need to employ different strategies. This article discusses some of those strategies. Method 1: Nai
4 min read
Python - Summation in Dual element Records List
Sometimes, while working with Records list, we can have problem in which we perform the summation of dual tuple records and store it in list. This kind of application can occur over various domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using list comprehension T
8 min read
Python | Tail Sliced List Summation
We often come to the situations in which we need to decrease the size of the list by truncating the last elements of the list and perform remaining list summation. This particular problem occurs when we need to optimize memory. This has its application in the day-day programming when sometimes we re
4 min read
Python - Tuple Matrix Columns Summation
Sometimes, while working with Tuple Matrix, we can have a problem in which we need to perform summation of each column of tuple matrix, at the element level. This kind of problem can have application in Data Science domains. Let's discuss certain ways in which this task can be performed. Input : tes
8 min read
Python | Summation of tuples in list
Sometimes, while working with records, we can have a problem in which we need to find the cumulative sum of all the values that are present in tuples. This can have applications in cases in which we deal with a lot of record data. Let's discuss certain ways in which this problem can be solved. Metho
7 min read
Python | Accumulative index summation in tuple list
Sometimes, while working with data, we can have a problem in which we need to find accumulative summation of each index in tuples. This problem can have applications in web development and competitive programming domain. Let's discuss certain way in which this problem can be solved. Method 1: Using
8 min read