0

Possible Duplicate:
Merging/adding lists in Python

nested_list= [[1, 3, 5], [3, 4, 5]]
sum_of_items_in_nested_list = [4, 7, 10]

I am trying to create a nested for loop that will add take the item at each corresponding index and add it to the other nested list at the same index. So the above adds nested_list[0][0] + nested_list[1][0], nested_list[0][1] + nested_list[1][1] and so on. I would like to do this without importing and modules. This is probably so easy but I am having the devil of a time with it.

1

3 Answers 3

4

use zip():

In [44]: nested_list= [[1, 3, 5], [3, 4, 5]]

In [45]: [sum(x) for x in zip(*nested_list)]
Out[45]: [4, 7, 10]

another way, using nested loops:

In [6]: nested_list= [[1, 3, 5], [3, 4, 5]]

In [7]: minn=min(map(len,nested_list))   #fetch the length of shorted list

In [8]: [sum(x[i] for x in nested_list) for i in range(minn)]
Out[8]: [4, 7, 10]
Sign up to request clarification or add additional context in comments.

3 Comments

How would you do this with using a nested for loop? I am trying to understand how to do this and I am just not "getting it"
@user1761521 nested for loop is not required for this.
@user1761521 I've added another approach for doing this with nested loops.
0

you may also think about this solution:

map(int.__add__,*nested_list)

Better style:

from operator import add
map(add,*nested_list)

Comments

0

Here is the answer for your case , and you can use len() to change the lengths of your lists.

nested_list= [[1, 3, 5], [3, 4, 5]]

sum_of_items_in_nested_list=[]
for j in range(0,3,1):
    result=0
    for i in range(0,2,1):
         result=result+nested_list[i][j]
         sum_of_items_in_nested_list = sum_of_items_in_nested_list + [result]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.