Python - List comprehension with 2 for loops & a ADD AND operand

Viewed 203
outgoing=[
        [27, 42, 66, 85, 65, 64, 68, 68, 77, 58],
        [24, 39, 58, 79, 60, 62, 67, 62, 55, 35],
        [3, 3, 8, 6, 5, 2, 1, 6, 22, 23],
        [3, 3, 8, 6, 5, 2, 1, 6, 22, 23],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       ]
incoming=[
        [459, 469, 549, 740, 695, 629, 780, 571, 574, 599],
        [420, 443, 504, 714, 669, 604, 745, 537, 537, 562],
        [39, 26, 45, 26, 26, 25, 35, 34, 37, 37],
        [26, 25, 27, 26, 26, 25, 35, 34, 37, 37],
        [13, 1, 18, 0, 0, 0, 0, 0, 0, 0],
       ]

I want to create a list which is the combination of incoming + outgoing. E.g incoming[0][0] should be added to outgoing[0][0], incoming[0][1] should be added to outgoing[0][1] and so on. A list called joint will be produced and have the exact same structure as incoming and outgoing (e.g a list of 5 lists of 10 elements). The code which does this is below:

joint=incoming
for x in range(5):
    for y in range(10):
        joint[x][y]+=outgoing[x][y]

This works fine. But I would like it as a list comprehension.

[[joint[x][y]+=outgoing[x][y]] for x in range(5) for y in range(10))]

The above doesn't work, can someone explain why this failed and give an example of a correct list comprehension.

3 Answers
Related