Home > front end >  Summing lists elements using zip
Summing lists elements using zip

Time:03-01

I am trying to sum up lists vertically but facing below issues. Example 1 below shows the sample how I need the output as. Example 2 below shows the problem I am facing.

Example 1:

list1 = [111]
list2 = [222]
sum_list = []

for (item1, item2) in zip(list1, list2):
    sum_list.append(item1 item2)

print(sum_list)    # [333]

Example 2:

inp = "1111 2222"
list1 = inp.split()
#print(list1)
list2 = [int(i) for i in list1]
print(list2)   # [1111, 2222]
out = [sum(item) for item in zip(list2)]

print(out)   # [1111, 2222]

I need the out as [3333] (as mentioned like Example 1 above) but it is printing as [1111, 2222].

CodePudding user response:

You should just sum list2 and put it inside an array.

inp = "1111 2222"
list1 = inp.split()
list2 = [int(i) for i in list1]
print(list2) # [1111, 2222]
out = [sum(list2)]

print(out)   # [333]
  • Related