How to dot product 1D and 2D lists in python without using NumPy or .dot?

With given 2D and 1D lists, I have to dot product them. But I have to calculate them without using .dot.

For example, I want to make these lists

matrix_A = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23], [24, 25, 26, 27], [28, 29, 30, 31]]
vector_x = [0, 1, 2, 3]

to this output

result_list = [ 14  38  62  86 110 134 158 182]

How can I do it by only using lists(not using NumPy array and .dot) in python?

>Solution :

You could use a list comprehension with nested for loops.

matrix_A = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23], [24, 25, 26, 27], [28, 29, 30, 31]]
vector_x = [0, 1, 2, 3]

result_list = [sum([a*b for a,b in zip(row, vector_x)]) for row in matrix_A]

print(result_list)

Output:

[14, 38, 62, 86, 110, 134, 158, 182]

Leave a Reply