How do I reverse a list using recursion in Python?

Question!

I want to have a function that will return the reverse of a list that it is given -- using recursion. How can I do that?

By : Alistair


Answers
def reverseList(listName,newList = None):
if newList == None:
    newList = []
if len(listName)>0:
    newList.append((listName.pop()))
    return reverseList(listName, newList)
else:
    return newList

print reverseList([1,2,3,4]) [4,3,2,1]



def revList(alist):
    if len(alist) == 1:       
        return alist #base case
    else:
        return revList(alist[1:]) + [alist[0]]

print revList([1,2,3,4])
#prints [4,3,2,1]


def reverse(q):
    if len(q) != 0:
        temp = q.pop(0)
        reverse(q)
        q.append(temp)
    return q
By : steve


This video can help you solving your question :)
By: admin