-3

I need help with creating a recursive function that multiplies all items in a list. Here is the code:

def multiply(lst):
    if len(lst) < 1:
        return 1
    else:
        for x in range(len(lst)):
            return lst[x] * multiply(lst[x+1])
Mr.Jod
  • 19
  • 1

1 Answers1

1

You don't need recursion and a loop. Either use recursion (not recommended, but as a demonstration):

# multiply([2,3,4]) == 2 * multiply([3,4])
#                   == 2 * (3 * multiply([4]))
#                   == 2 * (3 * (4 * multiply([])))
#                   == 2 * (3 * (4 * 1))
#                   == 2 * (3 * 4)
#                   == 2 * 12
#                   == 24
def multiply(lst):
    if not lst:
        return 1
    else:
        return lst[0] * multiply(lst[1:])

or a loop:

# multiply([2, 3, 4])
#  product = 1
#  product *= 2  (== 2)
#  product *= 3  (== 6)
#  product *= 4  (== 24)
def multiply(lst):
    product = 1
    for x in lst:
        product *= x
    return product
chepner
  • 497,756
  • 71
  • 530
  • 681