Skip to content

Python sum list of lists | Example code

  • by

Use the sum() function with a generator expression to get a 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)

Output:

Python sum list of lists

The sum of the list of lists and returns sum list

[[3,7,2],
    [1,4,5],
    [9,8,7]]
    _______
 >>>[13,19,14]

This uses a combination of zip and * 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)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *