0

I'm trying to make a function that takes two list of lists and returns the sum of their values.

Let's say I have 2 lists:

list1 = [[7,8], []]
list2 = [[3,4,2],[6,9]]

Expected output:

[[10,12,2],[6,9]]

Or another 2 lists:

list1 = [[], []]
list2 = [[3,4,2],[6,9]]

Expected output:

[[3,4,2],[6,9]] 

I think using list comprehension would be the most effective way to accomplish this, but I'm not as familiar with list comprehension as I'd like to be.

I've looked on Stack Overflow, and the closest answer I can find to this question is only with 2 lists that don't contain another list.

Joel
  • 1,564
  • 7
  • 12
  • 20
Caleb Collier
  • 71
  • 2
  • 9
  • 1
    Have you made any progress to solving this without loat comprehensions? If so, please show it and any associated errors. – roganjosh Nov 01 '18 at 19:10
  • 1
    Possible duplicate of [Add SUM of values of two LISTS into new LIST](https://stackoverflow.com/questions/14050824/add-sum-of-values-of-two-lists-into-new-list) – BenG Nov 01 '18 at 19:10
  • @BenG-TW, that duplicate does not consider the unequal sizes of the lists – sacuL Nov 01 '18 at 19:13

1 Answers1

3

You can use nested list comprehensions with zip and itertools.zip_longest:

import itertools
list1 = [[7,8], []]
list2 = [[3,4,2],[6,9]]

>>> [[x+y for x,y in itertools.zip_longest(i1,i2,fillvalue=0)] for i1,i2 in zip(list1,list2)]
[[10, 12, 2], [6, 9]]

list1 = [[], []]
list2 = [[3,4,2],[6,9]]

>>>[[x+y for x,y in itertools.zip_longest(i1,i2,fillvalue=0)] for i1,i2 in zip(list1,list2)]
[[3, 4, 2], [6, 9]]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
sacuL
  • 49,704
  • 8
  • 81
  • 106