In a list list, how to sum each item of each list with the item of its respective position?

Asked

Viewed 52 times

2

For ex my list is:

x = [[1,2,3,4,5],[6,7,8,9]]

How can I create a new list so that its elements are the sums of the corresponding elements in each list?

y = [1+6,2+7,3+8,4+9,5+0]
  • Hello Sander! Welcome to the community! I edited your question to make it clearer. Please review my response and mark how you accept if it meets your expectations.

  • https://answall.com/q/365456/112052

1 answer

5

Well, in this case the lists can have different sizes, so we need to fill the positions of the smallest lists and then add the corresponding values. We can do this using zip_longest with fillvalue to fill in the shortest lists:

x = [[1,2,3,4,5],[6,7,8,9]]
from itertools import zip_longest
y = [sum(x) for x in zip_longest(*x, fillvalue=0)]
print(y)
# [7, 9, 11, 13, 5]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.