user3287712
user3287712

Reputation: 57

Sum a list of lists to get a sum list Python

I'm trying to create a define a helper function that sums a list of lists to get a sum list.

For example:

[[1,2,3],[1,2,3],[2,3,4]]

Would come out as:

[4,7,10]

I found this on another post to work:

[sum(i) for i in zip(*listoflists)]

I need to to translate this into a defined function. This is what I have so far but it's not working.

def addhours(listoflists):
    for list in zip(*listoflists):
        newsum = sum (list)
return newsum

Upvotes: 1

Views: 224

Answers (2)

miku
miku

Reputation: 188004

Since the function is quite small, you could also use an anonymous definition:

>>> addhours = lambda l: [sum(i) for i in zip(*l)]
>>> addhours([[1,2,3],[1,2,3],[2,3,4]])
>>> [4,7,10]

Upvotes: 3

falsetru
falsetru

Reputation: 368894

Just put the list comprehension inside the function. (with return)

>>> def addhours(listoflists):
...     return [sum(lst) for lst in zip(*listoflists)]
...
>>> addhours([[1,2,3],[1,2,3],[2,3,4]])
[4, 7, 10]

Why your code does not work?

def addhours(listoflists):
    for list in zip(*listoflists):
        newsum = sum (list)  # <---- This statement overwrites newsum
    return newsum # returns the last sum.

You need a list to hold sums as items.

def addhours(listoflists):
    result = []
    for lst in zip(*listoflists):
        result.append(sum(lst)) # Append to the list instead of overwriting.
    return result

BTW, don't use list as a variable name. It shadows builtin function list.

Upvotes: 3

Related Questions