Product in list

Define a function called product that takes a list of integers as input and returns the product of all of the elements in the list.

def product (numbers):
for n in numbers:
n*= n

return n

print product ([1,2])

WHY IS MY RESULT 4 INSTEAD OF 2?

Hi, @yushan6714638042. Let’s see what happens in your function:

First time around:

for n in numbers: sets n to 1, so n*= n sets n to 1

Second time around:

for n in numbers: sets n to 2, so n*= n sets n to 4, the number that is returned in the next line

To do what you want, you need to bring in another variable to preserve the running product.

1 Like