Python: How to multiply all items in a list without using any prebuilt function

for-looploopspython

I know that I should be using a for loop, but I can´t figure out how exactly.

def product_list(list):
    for item in list:

I´ve search about this isse, but i´ve found replies that involves map() and lambda. How may I do it with a loop?

Best Answer

Use a temporary variable, and multiply each item to it:

def product_list(my_list):  # Don't use `list` as variable name
    product = 1
    for item in my_list:
        product *= item
    return product

A better way would be to use reduce() with operator.mul:

import operator

def product_list(my_list):
    return reduce(operator.mul, my_list, 1)