ADev
ADev

Reputation: 351

Multiply two list of different sizes element wise without using libraries in python

#create a simple list in python
#list comprehension
x = [i for i in range(100)]
print (x)

#using loops
squares = []
for x in range(10):
    squares.append(x**2)

print (squares)

multiples = k*[z for z in x] for k in squares

So in the last line of code I am trying to multiply both the lists. the problem is the lists are not of the same side and k*[z for z in x] this part is also incorrect.

Upvotes: 2

Views: 1310

Answers (3)

Maarten Fabré
Maarten Fabré

Reputation: 7058

For problems with iteration, I suggest anyone to check Loop Like A Native by Ned Batchelder and Looping like a Pro by David Baumgold

Option 1

If you want to multiply them as far as the shortest list goes, zip is your friend:

multiples = [a * b for a, b in zip (x, squares)]

Option 2

If you want a matrix with the product, then you can do it like this

result = [
    [a * b for a in x]
    for b in squares
]

Upvotes: 1

Martin Wettstein
Martin Wettstein

Reputation: 2894

I don't quite understand what the desired output would be. As the function stands now, you would have a list of lists, where the first element has 100 elements, the second one 400, the third 900, and so on.

  • One thing that's strange: The expression [z for z in x] defines a list that is identical to x. So, you might just write k*x
  • If you want to multiply the elements of both lists, you would have to write [[k*z for z in x] for k in squares]. This would lead to a list of 10 lists of 100 elements (or a 10x100-matrix) containing the products of your lists.
  • If you want to have one list of length 100 in the end that holds some kind of products, you will have to think about how to proceed with the shorter list.
  • EDIT: Or if you want to multiply them as far as possible until you reach the end of the shorter list, FRANCOIS CYRIL's solution is an elegant way to do so.

Upvotes: 1

Cyril FRANCOIS
Cyril FRANCOIS

Reputation: 88

You can loop on each array to multiply element by element at the same position in a result array:

i = 0
arrayRes = []
while i < min (len(array1),len(array2)):
    arrayRes.append(array1[i]*array2[i])
    i+=1

Or do you prefer to multiply them, matrix way?

x = 0
y = 0
arrayRes = []
while x < len(array1):
    arrayRes.append([])
    while y < len(array2):
        arrayRes[x].append(array1[x]*array2[y])
        y+=1
    x+=1

Upvotes: -1

Related Questions