+ 3

better idea? handling lists

i have 2 lists, with same length: a=[1,2,3] , b=[5,7,9] and i want output like this: c=[1+5, 2+7, 3+9], equal to [6,9,12] my best method is: c=[a[i]+b[i] for i in range(len(a))] but there should be better answer thanks for your attention

15th Jan 2020, 12:18 PM
post
post - avatar
6 ответов
+ 9
c = [x+y for x, y in zip(a, b)]
15th Jan 2020, 12:20 PM
HonFu
HonFu - avatar
+ 6
#Also this works: c = list(map(lambda x, y: x + y, a, b))
15th Jan 2020, 1:09 PM
Seb TheS
Seb TheS - avatar
+ 3
And if you have lists of lists ,you can add them like this lists_of_lists = [[1, 2, 3], [4, 5, 6]] print(sum(x) for x in zip(*lists_of_lists) #prints [5,7,9]
15th Jan 2020, 4:13 PM
Elliot
Elliot - avatar
+ 2
I think answer of both HonFu and Seb TheS are good
15th Jan 2020, 1:32 PM
Elliot
Elliot - avatar
+ 1
there's a better solution: import numpy as np numpy arrays are vastly superior in terms of performance and handling when it comes to arithmetic operations. https://docs.scipy.org/doc/numpy/reference/generated/numpy.add.html
16th Jan 2020, 11:57 PM
grdr
0
This works perfectly and is simpler than zip c = list(map(lambda x, y: x + y, a, b))
17th Jan 2020, 7:25 AM
Roshni Bajpai