Jessica
Jessica

Reputation: 135

Adding two lists while checking length

I'm stuck on a question where I have to add 2 lists together while factoring in the length. For example, if list1 = [1,2] and list2 = [3,4,5] the answer would be [1+3,2+4,5] or [4,6,5].

What I have so far is:

def addsum(list1,list2):
    new_list = []
    if len(list1) > len(list2):
       new_list = list1[0:]+list2[0:]

I'm not really sure how to appraoch this question since I'm new to lists. Would appreciate the help!

Upvotes: 1

Views: 94

Answers (5)

Cyker
Cyker

Reputation: 10974

Documentation on zip_longest:

Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted.

Here's the code:

from itertools import zip_longest
[x + y for x, y in zip_longest([1,2], [3,4,5], fillvalue=0)]

Output:

[4, 6, 5]

Upvotes: 0

internetional
internetional

Reputation: 322

Although zip_longest is more neat, another possibility is to use a trial/error approach (if you are tired of "ifs"), as shown here:

def addsum(list1, list2):
    res = []
    i = 0
    while i < len(list1) or i < len(list2):
        try:
            res.append(list1[i]+list2[i])
        except IndexError:
            try: res.append(list1[i])
            except IndexError: res.append(list2[i])
        i += 1
    return res

Upvotes: 0

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160607

You should use zip_longest from itertools with a fillvalue of 0 in a list comprehension:

r = [sum(i) for i in zip_longest(list1, list2, fillvalue=0)]

zip_longest pairs the elements in the input lists (list1 and list2 here). If one list is smaller, pairs the remainding elements of the larger list with the value supplied as the fillvalue (which we assign to 0 here).

Now, r equals:

print(r) # [4, 6, 5]

Similarly, you could utilize map instead of the list-comp:

# Python 3.x
r = list(map(sum, zip_longest(list1, list2, fillvalue=0)))
# Python 2.7
r = map(sum, zip_longest(list1, list2, fillvalue=0))

and get the same result for r.

Upvotes: 2

Copperfield
Copperfield

Reputation: 8520

I would use the zip_longest solution too, but building in your code this is what I would do

def addsum(list1, list2):
    if len(list1) < len(list2):
        list1, list2 = list2, list1
    result=list(list1)
    for i,x in enumerate(list2):
        result[i] += x
    return result

first make sure that the first list is the longest, and if that is not the case exchange them, then make a copy of longest list and finally add the elements of the shorter list position-wise to the copy and return it

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

Upvotes: 0

ahmet hamza emra
ahmet hamza emra

Reputation: 640

Poor man's approach:

def addsum(list1,list2):
    if len(list1) >= len(list2): 
        for i in range(len(list2)):
            list1[i]=list1[i]+list2[i]
        return list1
    else:
        for i in range(len(list1)):
            list2[i]=list1[i]+list2[i]
        return list2

Upvotes: 0

Related Questions