1

The inputs will be lists (which is the number of list is indefinite), the function is supposed to iterate through all the index and add each value of the list for same index for all the inputted list mathematically together. The output will be the a list which consist of all the added values

For example: lista = [1,2,3] listb = [2,3,5] listc = [-3,2,1] outputlist = [0,7,9] My function below is only able to add 2 list together, I want no restrictions as to how many list. How do I do that? Thank you very much in advance

def listadd(a,b):
    counter = 0
    list = []
    while counter < len(a):
        list.append(a[counter]+b[counter])
        counter += 1
    return list
Royston Teo
  • 121
  • 1
  • 1
  • 5

1 Answers1

2

You can use map with zip:

def listadd_new(*lsts):
    return list(map(sum, zip(*lsts)))

assert listadd([1, 2, 3], [4, 5, 6]) == listadd_new([1, 2, 3], [4, 5, 6])
jpp
  • 159,742
  • 34
  • 281
  • 339