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
OR you can use
zip
:You can create a function to find sum of nested lists:
@Kasara and @Bhargav also have some neat answers , check them out!
To get the sum of all the first elements you need to have a generator expression
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
Or you can call the
__next__
method as list is an iterable (If Py3)For python beginners:
By normal
for
loop and use try and except to handle exception when bested list is empty.Something like this is easy with
numpy
: