user4388084
user4388084

Reputation:

Sum of a list whose elements are themselves lists

Suppose i have a list;

list1 = [[1,2,3],[5,6,7], [7,8,9]]

When i execute the following line of code

for x in list1: sum(x)

I receive

6
18
24

I would like to sum all numbers in list1 using one comprehension and two sum() methods. That will also work if one of the list elements is a list of float objects.

Upvotes: 0

Views: 94

Answers (2)

Kasravnd
Kasravnd

Reputation: 107347

As an alternative answer you can sum all the inner list with reduce then calculate the sum :

>>> sum(reduce(lambda x,y :x+y,list1))
48

Upvotes: 0

Abhinav Ramakrishnan
Abhinav Ramakrishnan

Reputation: 1090

This should work:

sum([sum(x) for x in list1])

Upvotes: 5

Related Questions