Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum of first value in nested list

In traditional python, the sum function gives the sum of a list:

sum([0,1,2,3,4])=10

On the other hand, what if you have a nested list as so:

sum([[1,2,3],[4,5,6],[7,8,9]])

We find the error:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'

In addition to this, how could we find the sum of the first values (index 0) in a nested list? Such as:

something([[1,2,3],[4,5,6],[7,8,9]])=12
like image 684
user2592835 Avatar asked Feb 01 '15 16:02

user2592835


2 Answers

To get the sum of all the first elements you need to have a generator expression

>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> sum(i[0] for i in a)
12

You are getting unsupported operand type(s) for +: 'int' and 'list' because you are trying to add the three lists which is not the desired behavior.

If you want a list of first elements and then find their sum, you can try a list comprehension instead

>>> l = [i[0] for i in a]
>>> l
[1, 4, 7]
>>> sum(l)
12

Or you can call the __next__ method as list is an iterable (If Py3)

>>> sum(zip(*a).__next__())
12
like image 177
Bhargav Rao Avatar answered Nov 13 '22 17:11

Bhargav Rao


OR you can use zip :

>>> l=[[1,2,3],[4,5,6],[7,8,9]]
>>> sum(zip(*l)[0])
12
like image 1
Mazdak Avatar answered Nov 13 '22 16:11

Mazdak