Dawit Eshetu
Dawit Eshetu

Reputation: 49

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'

Upvotes: 2

Views: 146

Answers (1)

trincot
trincot

Reputation: 350310

You can use nested list comprehension:

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

Upvotes: 1

Related Questions