15.5 - Factorial - error message unclear


I'm working on the 'Factorial' exercise, & I'm receiving an error that has me a bit puzzled. When I 'save & submit', the interpreter comes back with "list assignment index out of range". I understand the basic message that it's trying to convey,but is there any way to tell if it's pointing to line 3, line 4, or line 6??

Line 3 - trying to instantiate an empty list.
Line 4 - trying to populate the 1st item in that list with the value of 'x'
Line 6 - trying to populate the remainder of the list with each number from 'x - 1' to 1.

I'd appreciate any clarification that could be provided. Thanks.


factorial(1) resulted in an error: list assignment index out of range

def factorial(x):
    total = 0
    numlist = []
    numlist[0] = x
    while x >= 2:
        x -= 1
    for i in numlist:
        total = total + i
    return total


You're overthinking this. Try following this template:

    if PARAMETER == 1:
        return 1

Make sure not to just follow the template and move on. I want to make sure that you understand how and why this works. If you have any questions, just ask.


Hey, big thanks for the quick response! :+1: Looking over the template that you provided, your way is blindingly simple compared to what I was trying to do. Thanks again.


I have to say I don't understand why this works?
The value of parameter isn't changing after the first calculation is it?

say parameter =4
the else statement is then: 4*3 = 12
but then there is no parameter = parameter -1
how does it then know to go 12 *2 ?

sorry if its obvious.


Hi carmenwmake, thank you for posting, & prompting me to think through this again!

As I understand it, the line 'return PARAMETER * FUNCTION(PARAMETER - 1)' is what performs the looping. It's doing this by essentially "calling itself" again for each value of x that is greater than 1. If you replace the word FUNCTION with FACTORIAL it might make more sense.

I am not claiming that's an authoritative answer - I could very well be wrong - but that's the way that I understand it. (And I'm sure that if that's wrong, someone will chime in with a correction.) :wink:


You are absolutely correct @codetimcode. This is what is known as recursion.


Thank you @codetimcode and @aquaphoenix17 for the help.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.