1

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.

philomath
  • 23
  • 5
  • 2
    you use `for index`, then `a[i]`, this should be the same variable. Also don't `return` in the loop, accumulate in a list and return afterwards. Easier approach: `[x*y for x, y in zip(a, b)]` – mozway Jan 23 '23 at 16:03
  • `i` and `index`. – tadman Jan 23 '23 at 16:03
  • 1
    Does this answer your question? [Element-wise addition of 2 lists?](https://stackoverflow.com/questions/18713321/element-wise-addition-of-2-lists) (Note: Change the addition to multiplication) – Abdul Aziz Barkat Jan 23 '23 at 16:06
  • 1
    forgot to change it back. Question has been edited to reflect this @tadman – philomath Jan 23 '23 at 16:06
  • `return` exits the function immediately. So you will only get a list with the product of the first two elements. – Code-Apprentice Jan 23 '23 at 16:09

1 Answers1

6

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)]
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Unmitigated
  • 76,500
  • 11
  • 62
  • 80