0

Consider these two lists:

a = [1, 2, 3]
b = [4, 5, 6]

The following line gives me the sum of elements in the same index:

c = [a + b for a, b in zip(a, b)]

Now I have:

[5, 7, 9]

Here is the problem:

my_list = [[1, 0, 1], [-1, 0, 0], ...]

How do I apply list comprehension to sum up a dynamic number of sublists and return a single list like above?

  • what's the problem in `my_list = [[1, 0, 1], [-1, 0, 0], ...]` ? You want sum of element at each index for all the sub list in the list? And your problem is that you don't know how many sublists are present in your list? – Moinuddin Quadri Aug 11 '21 at 21:20
  • 5
    `[sum(t) for t in zip(*my_list)]` – ddejohn Aug 11 '21 at 21:20
  • Yes, the number of sublists changes (so I could not specify with "a + b" as in the example). – codequestion Aug 11 '21 at 21:31

1 Answers1

-1

You can use map() with sum() and zip() to achieve this as:

>>> my_list = [[1, 0, 1], [-1, 0, 0], [1, 2, 3]]
>>> list(map(sum, zip(*my_list)))
[1, 2, 4]

OR, you can use zip with a list comprehension as:

>>> [sum(l) for l in zip(*my_list)]
[1, 2, 4]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126