Search code examples
pythonlistlist-comprehension

Multiplying 2D list by 1D list to each elements


I want to multiply a one dimensional list with a two dimensional list's elements. How can I do it with list comprehension?

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

The desired result is

c = [[3,8],[5,12]

I have tried this way

c = [i*j for i, j in zip(a,b)]

The error that I encountered was

TypeError: can't multiply sequence by non-int of type 'list'


Solution

  • You can use nested list comprehension:

    c = [ [x * y for x, y in zip(a, row)] for row in b ]