Use sum() function with a generator expression to get sum list of lists in Python.
sum(sum(x) for x in list)
Python sum list of lists example
Simple example code.
lis = [[1, 2], [3, 4], [5, 6]] res = sum(sum(x) for x in lis) print("Sum list of lists:", res)
Sum of list of lists and returns sum list
[[3,7,2], [1,4,5], [9,8,7]] _______ >>>[13,19,14]
This uses a combination of
* to unpack the list and then zip the items according to their index. You then use a list comprehension to iterate through the groups of similar indices, summing them and returning in their ‘original’ position.
l = [[3, 7, 2], [1, 4, 5], [9, 8, 7]] res = [sum(i) for i in zip(*l)] print(res)
Output: [13, 19, 14]
Do comment if you have any doubts or suggestions on this Python sum topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.