1

For example, one list is [[1,2,3],[4,5,6]]. The second list is [[2,3,4],[3,4,5]] and then I want to 1 + 2 =3 2+ 3 =5..... finally it becomes a new list : [[3,5,7],[7,9,11] and return the new list?

If I have two table, table 1 and table 2, then I create a new table 3 and add the value of each element in table1 to the value of the corresponding element of table2 and store the sum at the same location in table 3

Hobby
  • 61
  • 1
  • 9
  • You use `+`, just like you've suggested. What even is the question here? – Two-Bit Alchemist Feb 24 '16 at 20:22
  • Possible duplicate of [How to iterate through a list of lists in python?](http://stackoverflow.com/questions/9151104/how-to-iterate-through-a-list-of-lists-in-python) – Two-Bit Alchemist Feb 24 '16 at 20:23
  • @Two-BitAlchemist If I have two table, table 1 and table 2, then I create a new table 3 and add the value of each element in table1 to the value of the corresponding element of table2 and store the sum at the same location in table 3 – Hobby Feb 24 '16 at 20:33
  • You do it in 3 steps: iterate over the lists, add the corresponding values, add sum to new lists. If iterating over the lists ("tables") is the point of confusion, see the dupe target I linked. If constructing the new list is the problem, there's presumably another duplicate that explains. – Two-Bit Alchemist Feb 24 '16 at 20:35
  • (PS if the answer below helps you, use it. From SO's perspective this has been asked before and we'd like to find a link to where it was answered.) – Two-Bit Alchemist Feb 24 '16 at 20:47

1 Answers1

2

Option 1: Using list comprehension:

add_matrices = lambda m1,m2: [[x+y for x,y in zip(v1,v2)] for v1,v2 in zip(m1,m2)]
add_matrices ([[1,2,3],[4,5,6]],[[2,3,4],[3,4,5]])

Option 2: Using Numpy

import numpy as np
np.array([[1,2,3],[4,5,6]])+np.array([[2,3,4],[3,4,5]])
Uri Goren
  • 13,386
  • 6
  • 58
  • 110