Python - Sum of different length Lists of list
Last Updated :
08 May, 2023
Getting the sum of list is quite common problem and has been dealt with and discussed many times, but sometimes, we require to better it and total sum, i.e. including those of nested list as well. Let’s try and get the total sum and solve this particular problem.
Method #1 : Using list comprehension + sum() We can solve this problem using the list comprehension as a potential shorthand to the conventional loops that we may use to perform this particular task. We just iterate and sum the nested list and at end return the cumulative sum using sum function.
Python3
# Python3 code to demonstrate
# Sum of Uneven Lists of list
# Using list comprehension + sum()
# initializing list
test_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
# printing original list
print("The original list : " + str(test_list))
# using list comprehension + sum()
# Sum of Uneven Lists of list
res = sum([ele for sub in test_list for ele in sub])
# print result
print("The total element sum in lists is : " + str(res))
Output : The original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
The total element sum in lists is : 80
Time Complexity: O(n),The above code iterates through the list once, hence the time complexity is linear, i.e. O(n).
Space Complexity: O(n),The algorithm uses an additional list to store the result, thus consuming linear space which is O(n).
Method #2 : Using chain() + sum() This particular problem can also be solved using the chain function instead of list comprehension in which we use the conventional sum function to check the sum.
Python3
# Python3 code to demonstrate
# Sum of Uneven Lists of list
# Using chain() + sum()
from itertools import chain
# initializing list
test_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
# printing original list
print("The original list : " + str(test_list))
# using chain() + sum()
# Sum of Uneven Lists of list
res = sum(list(chain(*test_list)))
# print result
print("The total element sum in lists is : " + str(res))
Output : The original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
The total element sum in lists is : 80
Time Complexity: O(n) where n is the number of elements in the string list. The chain() + sum() is used to perform the task and it takes O(n) time.
Auxiliary Space: O(1) constant additional space is required.
Method #3 : Using numpy.sum() and numpy.flatten()
Note: Install numpy module using command "pip install numpy"
Python3
import numpy as np
# initializing list
test_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
# printing original list
print("The original list : " + str(test_list))
# Using numpy.concatenate() and numpy.sum()
res = np.sum(np.concatenate([np.array(sublist) for sublist in test_list]))
# print result
print("The total element sum in lists is : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
Output:
The original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
The total element sum in lists is : 80
Time Complexity: O(n) where n is the total number of elements in the nested list
Auxiliary Space : O(n) for storing the concatenated array.
Method #4: Using reduce() from functools module
Python3
from functools import reduce
# initializing list
test_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
# printing original list
print("The original list : " + str(test_list))
# using reduce() from functools module
# Sum of Uneven Lists of list
res = reduce(lambda x,y: x+y, [ele for sub in test_list for ele in sub])
# print result
print("The total element sum in lists is : " + str(res))
OutputThe original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
The total element sum in lists is : 80
Time complexity: O(N), where N is the total number of elements in all sub-lists of test_list.
Auxiliary space complexity: O(N), as we create a new list with all the elements from the sub-lists using list comprehension, and then pass it to reduce().
Method #5 : Using sum() and extend() methods
Approach
- Convert the nested list to single list using extend(),for loop and store in x
- Find the sum of x using sum() and store in res
- Display res
Python3
# Python3 code to demonstrate
# Sum of Uneven Lists of list
# initializing list
test_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
# printing original list
print("The original list : " + str(test_list))
# Sum of Uneven Lists of list
x=[]
for i in test_list:
x.extend(i)
res=sum(x)
# print result
print("The total element sum in lists is : " + str(res))
OutputThe original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
The total element sum in lists is : 80
Time Complexity : O(N) N - length of x
Auxiliary Space: O(1) since we are using single variable res to store sum
Similar Reads
Python - Interleave multiple lists of same length
When we interleave multiple lists, we mix the items from each list so that they alternate in a new sequence. This is often done when we have lists of the same length and want to combine them, with each item from each list appearing one after another. In this article, we will explore interleaving mul
2 min read
Python Initialize List of Lists
A list of lists in Python is often used to represent multidimensional data such as rows and columns of a matrix. Initializing a list of lists can be done in several ways each suited to specific requirements such as fixed-size lists or dynamic lists. Let's explore the most efficient and commonly used
3 min read
Flatten a List of Lists in Python
Flattening a list of lists means turning a nested list structure into a single flat list. This can be useful when we need to process or analyze the data in a simpler format. In this article, we will explore various approaches to Flatten a list of Lists in Python.Using itertools.chain itertools modul
3 min read
Python - Convert a list into tuple of lists
When working with data structures in Python, there are times when we need to convert a list into a tuple of smaller lists.For example, given a list [1, 2, 3, 4, 5, 6], we may want to split it into a tuple of two lists like ([1, 2, 3], [4, 5, 6]). We will explore different methods to achieve this con
3 min read
Convert 1D list to 2D list of variable length- Python
The task of converting a 1D list to a 2D list of variable length in Python involves dynamically dividing a single list into multiple sublists, where each sublist has a different number of elements based on a specified set of lengths.For example, given a list [1, 2, 3, 4, 5, 6] and length specificati
4 min read
Python - Find maximum length sub-list in a nested list
In Python, we often work with nested lists (lists inside lists), and sometimes we need to find out which sub-list has the most items. In this article, we will explore Various methods to Find the maximum length of a sub-list in a nested list. Using max() Function with key=lenThe simplest and most eff
2 min read
Find Sum and Average of List in Python
Our goal is to find sum and average of List in Python. The simplest way to do is by using a built-in method sum() and len(). For example, list of numbers is, [10, 20, 30, 40, 50] the sum is the total of all these numbers and the average is the sum divided by the number of elements in the list.Using
2 min read
Sum of number digits in List in Python
Our goal is to calculate the sum of digits for each number in a list in Python. This can be done by iterating through each number, converting it to a string, and summing its digits individually. We can achieve this using Pythonâs built-in functions like sum(), map(), and list comprehensions. For exa
2 min read
Python program to find sum of elements in list
Finding the sum of elements in a list means adding all the values together to get a single total. For example, given a list like [10, 20, 30, 40, 50], you might want to calculate the total sum, which is 150. Let's explore these different methods to do this efficiently.Using sum()sum() function is th
3 min read
Python - Sum of each List element occurrence in another
Sometimes, while working with Python, we can have a problem in which we need to get occurrence of 1 element in another. But as a modification of this, we can have a problem in which we need to count the occurrence of all elements of 1 list in another. Lets discuss certain ways in which this task can
6 min read