0

I'm trying to learn python and i'm doing some basic exercises like this one. I've tried using list comprehension, but the newly created list has only the sum of the first two elements. How can i put the remaining integers of L1 in L3 using list comprehension?

L1 = [3, 7, 1, 54]
L2 = [0, 128]
L3 = [x+y for x,y in zip(L1, L2)]
for i in L3:
    print(i, end= " ")
Onige
  • 1
  • What are you exactly trying to achieve ? Calculate the sum ? Put the sum in a new list, etc ? – ApplePie Feb 23 '21 at 11:23
  • Take a look at https://stackoverflow.com/a/1277311/3186769. – pradeepcep Feb 23 '21 at 11:25
  • Please [edit] your question to clarify what result you expect. There are only 2 elements in L2; it is not possible to do a pairwise addition with L2 and get more than 2 resuls without defining what value to use after L2 has ended. – MisterMiyagi Feb 23 '21 at 11:25
  • Does this answer your question? [Is there a zip-like function that pads to longest length in Python?](https://stackoverflow.com/questions/1277278/is-there-a-zip-like-function-that-pads-to-longest-length-in-python) – Yulian Feb 23 '21 at 11:40

2 Answers2

0

One way to make your code work is to extend the array L2 to the length of L1, e.g. to fill it with zeros:

L1 = [3, 7, 1, 54]
L2 = [0, 128]

# extend the L2 array by the difference in length of both arrays.
L2.extend([0] * (len(L1) - len(L2)))

L3 = [x+y for x,y in zip(L1, L2)]
for i in L3:
    print(i, end= " ")

Another apporach is to use itertools.zip_longest, see this answer.

Yulian
  • 365
  • 4
  • 12
0

Below code will work.

import itertools


def add_data(list1, list2):
    temp_list= list(itertools.zip_longest(list1, list2, fillvalue= 0))
    return [x+y for x,y in temp_list]


if __name__ == '__main__':
    l3= add_data([3, 7, 1, 54],[0, 128])
    print(l3)