I'm trying to figure out how to print out a list in reverse order using recursion. This is how I reversed a list:
def reverse_list(xs):
if xs == []:
return xs
else:
new_list = (print_reverse (xs[1:])) + [xs[0]]
return new_list
and this is how I printed a list in order:
def print_in_order(l, i = 0):
if i < len(l):
print (l[i])
print_in_order(l, i + 1)
I tried just printing out from the new list inside the function like this:
def print_reverse(xs):
if xs == []:
return xs
else:
new_list = (print_reverse (xs[1:])) + [xs[0]]
for number in new_list:
print (number)
But it raises an error. How do you combine the two processes?
print_in_order? start fromlen(l) - 1and checkif i >= 0?print_in_orderstarts fromi = 0i.e. from the beginning of the string,print_in_reverseshould start fromi = len(l) - 1- from the last character of the string. Side note: Do not uselwhen it's easy to mix it with1i = Noneassign it tolen(l) - 1?