Abhinav Kumar
Abhinav Kumar

Reputation: 1682

Summing two lists NOT element wise in python without using for loop

I am trying to add two lists without using a for loop (inbuilt function? , generators?)

For example let us use the following lists:

a = [1,2,3]
b = [10,15,19]

I want the following result:

c = [11,12,13,16,17,18,20,21,22]

How can I accomplish this? Please keep in mind that using a loop structure will give the result I am looking for but since I am working with pretty big lists, I want a smarter way of doing this.

Upvotes: 0

Views: 177

Answers (3)

hpaulj
hpaulj

Reputation: 231375

If numpy is available:

import numpy as np
print (np.array(a)+np.array(b)[:,None]).flatten().tolist()
# [11, 12, 13, 16, 17, 18, 20, 21, 22]

This still uses iteration, but it is buried in the numpy C code.

This calculates an outer sum, and then flattens it and turns it back into a list

array([[11, 12, 13],
       [16, 17, 18],
       [20, 21, 22]])

Upvotes: 0

aensm
aensm

Reputation: 3607

This uses a for loop, but it's compact:

[i + j for i in b for j in a ]

Upvotes: 1

Mark Reed
Mark Reed

Reputation: 95252

This works:

import itertools
a = [1,2,3]
b = [10,15,19]
[x+y for x,y in itertools.product(b,a)]
#>> [11, 12, 13, 16, 17, 18, 20, 21, 22]

Upvotes: 3

Related Questions