Version written using fold idea
We need a function that we will call minus (this comes from the lisp / scheme, etc.). It takes an element and a list and adds that element to the head (beginning) of the list. Note that in python this is inefficient.
def cons(x,xs): return [x] + xs
Now the fold function (strictly speaking, the left fold). This is a function in its own right and can be used for many things (see Link), the python equivalent will probably be reduce . Note that it takes a function f and applies this function to the list header and the variable acc (short for battery)
def foldl(f,acc,xs): if not xs: return acc head, *tail = xs return foldl(f, f(head,acc), tail)
Now we can write a version of the inverse that is recursive (since fold is recursive)
def reverse(xs): return foldl(cons, [], xs)
Thus, the code embodies the idea of a recursive function. For example, if we wanted to recursively summarize a list of numbers, we could define it as:
from operator import add
If we defined the right fold, then:
def foldr(f,acc,xs): if not xs: return acc head, *tail = xs return f(head, foldr(f, acc, tail))
Then calling foldr(cons, [], xs) returns a list identical to the first.