How to multiply each digit of an array in the same index in Python?

I have to make this program that multiplies an like this:
The first number of the first list of the first array with the first number of the first list of the second array. For example:

array1 = [[1,2,3], [3,2,1]]
array2 = [[4,2,5], [5,6,7]]

So my output must be:

result = [[4,4,15],[15,12,7]]

So far my code is the following:

def multiplyArrays(array1,array2):
    if verifySameSize(array1,array2):
        for i in array1:
            for j in i:
                digitA1 = j
            for x in array2:
                for a in x:
                    digitA2 = a
            mult = digitA1 * digitA2
        return mult
    return 'Arrays must be the same size'

It’s safe to say it’s not working since the result I’m getting for the example I gave is 7 , not even an array, so, what am I doing wrong?

>Solution :

if you want a simple solution, use numpy:

import numpy as np

array1 = np.array([[1,2,3], [3,2,1]])
array2 = np.array([[4,2,5], [5,6,7]])

result = array1 * array2

if you want a general solution for your own understanding, then it becomes a bit harder: how in-depth do you want the implementation to be? there are many checks for example the same sizes, same types, number of dimensions, etc.

the problem in your code is using for each loop instead of indexing. for i in array1 runs twice, returning a list (first [1,2,3] then [3,2,1]). then you do a for each loop in each list returning a number, meaning you only get 1 number as the output which is the result of the last operation (1 * 7 = 7). You should create an empty list and append your results in a normal for loop (not for each).

so your function becomes:

def multiplyArrays(array1,array2):
    result = []
    for i in range(len(array1)):
        for j in range(len(array1[i])):
    return result

this is a bad idea though because it only works with 2D arrays and there are no checks. Avoid writing your own functions unless you absolutely need to.

Leave a Reply