BTurkeli
BTurkeli

Reputation: 103

Multiplication of a list and list of list

Mathematically I am trying to do a xij * yi multiplication. In Python, I need to multiply x and y lists as below:

x = [[1,2,3],[4,5,6],[7,8,9]]
y = [10,100,1000]

xy = [[] for i in range(3)]

for i in range(3):
   for j in range(3):
       xy[i][j] += [y[i] * x[i][j]]

However, I get "list index out of range" error while I expect to have the output as following:

xy = [[10, 20, 30],[400, 500, 600],[7000, 8000, 9000]]

Can you help?

Upvotes: 2

Views: 143

Answers (4)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Just simple list comprehensions:

x = [[1,2,3],[4,5,6],[7,8,9]]
y = [10,100,1000]

xy = [[y[i] * j for j in lst] for i, lst in enumerate(x)]
print(xy)

The output:

[[10, 20, 30], [400, 500, 600], [7000, 8000, 9000]]

Upvotes: 0

cph_sto
cph_sto

Reputation: 7587

Let's use numpy library's multiply() function to solve this problem with the help of List comprehensions -

import numpy as np
list([np.multiply(x[i],y[i]).tolist() for i in range(len(y))])
    [[10, 20, 30], [400, 500, 600], [7000, 8000, 9000]]

Upvotes: 0

Sheldore
Sheldore

Reputation: 39052

You were very close. The issue was that you were using double indices [i][j] to refer to your nested lists. You have to just use the index i. The rest of your code is perfectly fine.

x = [[1,2,3],[4,5,6],[7,8,9]]
y = [10,100,1000]

xy = [[] for i in range(3)]

for i in range(3):
    for j in range(3):
        xy[i] += [y[i] * x[i][j]]

# [[10, 20, 30], [400, 500, 600], [7000, 8000, 9000]]

Alternative is to use append

for i in range(3):
    for j in range(3):
        xy[i].append(y[i] * x[i][j])

Alternative using NumPy

import numpy as n
x = np.array([[1,2,3],[4,5,6],[7,8,9]])
y = np.array([10,100,1000])
xy = (x.T*y).T

Upvotes: 4

javan.rajpopat
javan.rajpopat

Reputation: 147

I think this will solve the problem,

x = [[1,2,3],[4,5,6],[7,8,9]] 
y = [10,100,1000]
xy = []
for i in range(3):
    xy.append([])
    for j in range(3):
        xy[i].append(y[i]*x[i][j])
print (xy)

In python, use 'list.append()' to add value to the list.

Upvotes: 0

Related Questions