hat
hat

Reputation: 223

Sum nested lists in Python

I have a nested list in python, i=[[1,2,3],[4,5,6]]. I want to sum the terms such that the final result is j=[1+4,2+5,6+3]. I have tried:

i=[[1,2,3],[4,5,6]]
j=[sum(x) for x in zip(i)]

But this is what I get instead:

>>>print j
[6, 15]

Upvotes: 2

Views: 592

Answers (2)

Valentin Lorentz
Valentin Lorentz

Reputation: 9753

zip does not take a list of lists as an argument. It takes an arbitrary long list of list arguments.

Here is how to do it:

i=[[1,2,3],[4,5,6]]
j=[sum(x) for x in zip(*i)]

Upvotes: 2

embert
embert

Reputation: 7592

You forgot the *

>>> i=[[1,2,3],[4,5,6]]
>>> [sum(x) for x in zip(*i)]
[5, 7, 9]

Upvotes: 1

Related Questions