Search code examples
pythonrecursioncomputer-science

How to recursively append to an empty list?


I'm new to recursion and finding it pretty difficult to grasp. I can't figure out how to append an empty array if I can't directly "touch" it. If its a string I would add the value each time. If it was a number that involved multiplication, I could multiply it each time, but with an array, I don't know what to do.

I dont know how to append to an empty array without being able to directly "touch" it.

This is what I've done so far:

def laugh(num):
  if num == 0:
    return []
  # This doesnt work since we can't append a function call. I'm unsure what to do.
  return laugh(num - 1).append("ha ")

print(laugh(3)) -> ["ha, ha, ha"]

If could do this easily if i could just return a string of "Ha"'s instead. I could return an empty string and just add a "Ha" for each step.


Solution

  • You can modify it like:

    def laugh(num):
        if num == 0:
            return []
        haha = laugh(num-1)
        haha.append("ha")
        return haha
    

    Since append does not return the modified list, you have to do it in two steps. Using concatenation and the ternary operator, you can shrink this to:

    def laugh(num):
        return laugh(num-1) + ["ha"] if num else []