0

I am baffled by this and I suspect I am making an extremely trivial mistake but here it is anyway:

I want to recursively fill a list with elements. Let's make a simple example. I just want to invert a list in the following manner:

def recurse(x, remaining):

    if len(remaining) == 0:
        assert x == [3, 2, 1] # This does not raise????
        return x
    x.append(remaining.pop())
    recurse(x, remaining)

x = [1, 2, 3]
y = recurse([], x)

However y is None, even when I explicitly check that the value is as expected JUST before returning. What am I missing?

pilu
  • 720
  • 5
  • 16

1 Answers1

2

Only the last call in your recursion does return something, the other calls all don't return anything. What you are missing is handing the return value through to the topmost call of the function like so:

def recurse(x, remaining):

    if len(remaining) == 0:
        assert x == [3, 2, 1] # This does not raise????
        return x
    x.append(remaining.pop())
    return recurse(x, remaining)

x = [1, 2, 3]
y = recurse([], x)
FlyingTeller
  • 17,638
  • 3
  • 38
  • 53
  • Also, the `assert` is not throwing any error because the only time it's executed, `x` has exactly that value `[3, 2, 1]` – raul.vila Apr 17 '18 at 11:53