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]
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]
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 python python-3.x list arraylist
You are not signed in. Login or sign up in order to post.
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.
– Jobert
https://answall.com/q/365456/112052
– hkotsubo