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.
>Solution :
Don’t return 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)]