'add two list index wise
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
Solution 1:[1]
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]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
