Martin Spasov
Martin Spasov

Reputation: 313

Add sum of values of two lists into new one

EDIT: Is it possible to be done without any imports?

This question already has an answer here but it doesn't mention what to do if the size of the lists is not the same

v1 = [1,2,3,4]
v2 = [1,2,3,4,5]

I need sum = [2,4,6,8,5]

I get a successful result from my code only if the lists are with the same size or [], but no success if the size is different no matter what i put in there

This is what I got

def addVectors(v1, v2):
    sum = []
    result = 0
    if len(v1) == 0 and len(v2) == 0:
        return sum
    elif len(v1) == len(v2) or len(v1) != len(v2):
        for i in range(len(v1)):
            result = v1[i] + v2[i]
            sum.append(result)

    return sum

Upvotes: 0

Views: 218

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124818

Use itertools.izip_longest() with the fill value set to 0:

from itertools import izip_longest

summed = [a + b for a, b in izip_longest(v1, v2, fillvalue=0)]

The izip_longest() documentation gives you a pure-python, no imports needed version, provided you also take the itertools.repeat() and itertools.chain() functions in their pure-python form.

Or you could do:

def addVectors(v1, v2):
    min_length = min(len(v1), len(v2))
    result = [a + b for a, b in zip(v1, v2)]
    return result + v1[min_length:] + v2[min_length:]

Demo:

>>> from itertools import izip_longest
>>> v1 = [1,2,3,4]
>>> v2 = [1,2,3,4,5]
>>> [a + b for a, b in izip_longest(v1, v2, fillvalue=0)]
[2, 4, 6, 8, 5]
>>> def addVectors(v1, v2):
...     min_length = min(len(v1), len(v2))
...     result = [a + b for a, b in zip(v1, v2)]
...     return result + v1[min_length:] + v2[min_length:]
... 
>>> addVectors(v1, v2)
[2, 4, 6, 8, 5]

Upvotes: 4

Jon Clements
Jon Clements

Reputation: 142226

You can use izip_longest with a fill value of 0:

from itertools import izip_longest

v1 = [1,2,3,4]
v2 = [1,2,3,4,5]
res = [sum(items) for items in izip_longest(v1, v2, fillvalue=0)]
# [2, 4, 6, 8, 5]

Upvotes: 4

Related Questions