Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading