Newbie
Newbie

Reputation: 376

Python: Print a list in reverse using recursion

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?

Upvotes: 0

Views: 2718

Answers (4)

John La Rooy
John La Rooy

Reputation: 304503

You just need to swap two lines:

def print_in_reverse(lst, i=0):
    if i < len(lst):
        print_in_reverse(lst, i + 1)  # Do the recursive call before you
        print (lst[i])              # print instead of after

Upvotes: 2

Carlo Beccarini
Carlo Beccarini

Reputation: 95

One of the simplest way to do this, it's using slicing in this way:

>>> example = [1, 2, 3, 4, 5]
>>> example[::-1]
[5, 4, 3, 2, 1]

..and if you want to print them, just do this:

>>> for number in example:
...     print(number)
...     
1
2
3
4
5

EDITED:

>>> example = [1, 2, 3, 4, 5]

>>> def recursive(list, counter=0):
...     if len(list) > counter:
...         print(list[counter])
...         recursive(list, counter+1)
...     return
... 

>>> recursive(example[::-1])
5
4
3
2
1

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186843

Something like that (print_in_order adaptation):

# print l in reverse order, starting from i
# note, that we're allowed not to specify i
def print_in_reverse(l, i = None):
    # if i is not specified    
    if (i is None):
        i = len(l) - 1 

    # we're printing in reverse: 
    # we have to check for beginning of the string instead of ending
    # that's why check for 0 
    if (i >= 0):
        print (l[i])
        print_in_reverse(l, i - 1) # reverse direction: i - 1 instead of i + 1

Upvotes: 0

Majlik
Majlik

Reputation: 1082

If you want just print it in reverse order and you don't want to change original list you can just modify print_in_order() like this:

#second parameter is length of list
def print_in_reversed(l, i): 
    if i > 0:
        print (l[i-1])
        print_in_order(l, i - 1)

And you will call it with this example

example = [1,2,3,4,5]    
print_in_order(example, len(example))

Upvotes: 0

Related Questions