I’m somewhat of a noob to python but I’m trying to create a recursive function which works just like the built in range function:
def Range (lo, hi):
if lo >= hi:
return []
else:
return [lo, Range (lo+1,hi)]
but its returning multiple lists.
Instead of [3,4,5,6], which is what I want, its returning [3,[4,[5,[6,[]]]]]
Why is this and how do I fix it?
When you recurse like that,
Rangereturns a list each time:In order to avoid this, add your lists together:
EDIT:
As @delnan points out, this function is very inefficient – it both recurses in a language without tail-call optimization* and it generates two (possibly three) new lists for each level of recursion. @mipadi’s answer is more performant because it creates only one list (the
accoraccumulatorargument) and passes it as it recurses.* This may not be true for the Python language, but I’m 99% sure it is true for the most common implementation of Python, namely CPython.