1

I'm looking for a way to use list comprehensions to achieve the following:

a = [1,2,3,4]
b = [5,6,7,8]
vals = []

for i in a:
  for j in b:
    vals.append(i*j)

print(vals)

I'm convinced there's a way to do this with list comprehension, but I'm at a loss for how to proceed.

zklim
  • 525
  • 1
  • 5
  • 9
  • vals = [i*j for i, j in zip(a,b)] – Osman Mamun Dec 22 '17 at 23:37
  • It may be a duplicate, but not of the one you mentioned - that solution gives me a list of lists; I'm not interested in having a list of lists, I want a list of all the values. Run my code and then the code you referenced and you'll see the difference. – zklim Dec 22 '17 at 23:40

2 Answers2

6

Pure list comprehension:

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

Output:

[5, 6, 7, 8, 10, 12, 14, 16, 15, 18, 21, 24, 20, 24, 28, 32]
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
  • 1
    I posted that answer then deleted because I saw something (that didn't exist). I think it is becoming late for me today :) +1 for the brain telematics! – progmatico Dec 22 '17 at 23:45
1

itertools' product will give you all the combinations of elements from both lists. You could then use a comprehension to multiply each pair:

from itertools import product
print([x[0] * x[1] for x in product(a, b)])
Mureinik
  • 297,002
  • 52
  • 306
  • 350