I've been a bit puzzled by the requirement to use a list: if we only need the total sum in the end, and there's no requirement to access previously passed parameter values, then why waste memory? This isThat's outright silly.
Unless, the assignment means to "use a list" in this way:
def make_accumulator():
lst = [0]
def acc(n):
lst[0] += n
return lst[0]
return acc
Instead of a list, you could use any other kind of object.
It just has to be an object, cannot be a simple value.
For example, it won't work with a simple integer variable, like total += total
, because that involves a reassignment (rebinding of a name),
which is very different from modification of an existing object.
For more details, see PEP227.
How can I think of writing pure functional code for above program (i.e., without any state change)?
You cannot. As per the requirements, the accumulator function may (and in practice, it typically will) return different values for the same input, which necessitates state. There's no way around it.