Home > Enterprise >  add two list index wise
add two list index wise

Time:03-31

If I run this code I'm getting some error that I don't know how to change

from itertools import zip_longest

a = input("enter the list 1:")
list1 = list(a.split(","))
b = input("enter the list 2:")
list2 = list(b.split(","))
if not list2:
    print(list1)
else:
    res = [i j for i,j in zip_longest(list1, list2, fillvalue=0)]
    print("Ans: ",res)

it shows error:

res = [i j for i,j in zip_longest(list1, list2, fillvalue=0)]
TypeError: unsupported operand type(s) for  : 'int' and 'str'

Expected output:

enter the list 1:1,2,3
enter the list 2:1,2,3,4,5
Ans : 2,4,6,4,5

CodePudding user response:

You could use itertools.zip_longest:

from itertools import zip_longest
out = [i j for i,j in zip_longest(test_list1, test_list2, fillvalue=0)]

Output:

[5, 8, 10, 2, 10]

CodePudding user response:

Use itertools.zip_longest() with sum(), which performs pairwise summation on the elements of both test_lists (using zero if the element doesn't exist, per fillvalue=0):

from itertools import zip_longest

test_list1 = [1, 3, 4]
test_list2 = [4, 5, 6, 2, 10]
  
print("Original list 1:", test_list1)
print("Original list 2:", test_list2)
res_list = [sum(item) for item in zip_longest(test_list1, test_list2, fillvalue=0)]
print("Resultant list is:", res_list)

This prints:

Original list 1: [1, 3, 4]
Original list 2: [4, 5, 6, 2, 10]
Resultant list is: [5, 8, 10, 2, 10]

Note that I've also modified the print statements to get rid of the explicit calls to str(). If you pass in multiple arguments to print(), they will be printed to the console, each separated by a space.

  • Related