0

Is it possible to recursively sum two lists element by element and then return the new list?

def sumListElements(listOne, listTwo):
    list = []
    i = 0
    while i < len(listOne):
        list.append(listOne[i] + listTwo[i])
        i += 1
    return list

So,

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

Results

R = [4, 6, 8]
Xerath
  • 1,029
  • 5
  • 15
  • 26

3 Answers3

3

Here is a recursive implementation

def recursive_sum(l1, l2, idx = 0):
    if idx < min(len(l1), len(l2)):
        return [l1[idx] + l2[idx]] + recursive_sum(l1, l2, idx + 1)
    else:
        return []

print recursive_sum([1, 2, 3], [4, 5, 6])
# [5, 7, 9]

Or

def recursive_sum(l1, l2, result = None, idx = 0):
    if result is None:
        result = []
    if idx < min(len(l1), len(l2)):
        result.append(l1[idx] + l2[idx])
        return recursive_sum(l1, l2, result, idx + 1)
    else:
        return result
thefourtheye
  • 221,210
  • 51
  • 432
  • 478
2

Use zip() and map() here:

R = map(sum, zip(a, b))

Demo:

>>> a = [1, 2, 3]
>>> b = [3, 4, 5]
>>> map(sum, zip(a, b))
[4, 6, 8]

For Python 3 compatibility, replace map() with a list comprehension:

[sum(z) for z in zip(a, b)]
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
1

Function which takes n lists, and adds each element in an i-th index together with the others:

from itertools import izip_longest

def sum_elements(*lists):
    return map(sum, izip_longest(*lists, fillvalue=0))

Showed with your data:

>>> sum_elements([1, 2, 3], [3, 4, 5])
[4, 6, 8]

Lists with uneven lengths still have a nice result:

>>> sum_elements([1, 2, 3], [3, 4, 5, 6])
[4, 6, 8, 6]

And it can take any number of lists:

>>> sum_elements([1, 2, 3], [3, 4, 5, 6], [8,9])
[12, 15, 8, 6]
Inbar Rose
  • 39,034
  • 24
  • 81
  • 124