printing a new list as product of elements in two lists


So i’m trying to define a function which given two lists of the same size, returns a new list with the product of each element at a given index.

a = [1, 2, 3]
b = [1, 4, 5]

def list_mult(a, b):
    if len(a) != len(b):
        print("error, lists must be the same size")

    for i in range(len(a)):
        return [a[i] * b[i]]

print(list_mult(a, b))

The code is running, but it is only returning [1]. Not sure why, as I was under the impression that this for loops iterates over all i’s in the range.

Asked By: philomath



Don’t return from inside the loop, as that will return after only 1 iteration. Keeping your current structure, you can instead add each product to a list and return that.

res = []
for i in range(len(a)):
    res.append(a[i] * b[i])
return res

Alternatively, use a list comprehension with zip.

return [x * y for x, y in zip(a, b)]
Answered By: Unmitigated

Here’s how I would solve the problem, catering for the edgecase of one array being larger than the other.

from typing import List

def multiply_arrays(a: List[int], b: List[int]):
    result = []

    for i in range(max(len(a), len(b))):
        item_a = a[i] if i < len(a) else 1
        item_b = b[i] if i < leb(b) else 1

        result.append(item_a * item_b)

    return result
Answered By: Tomisin Abiodun
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.