Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using recursion to reverse a list in python? [closed]

Is there an alternative way to reversing a list in python using recursion? Here is my code :

revList=[]
def reverseList(listXS):
    if(len(listXS)==1):
        revList.append(listXS[0])
    else:
        current=  listXS.pop()
        revList.append(current)
        reverseList(listXS)
    return revList

testList= ["mouse","dog","cat"]
print(testList)
print(reverseList(testList))
like image 849
Michael André Slimz Avatar asked Sep 03 '26 15:09

Michael André Slimz


2 Answers

If you want an alternative recursive approach:

def reverseList(listXS):
    return [] if not listXS else [listXS.pop()] + reverseList(listXS)

Or slicing:

def reverseList(listXS):
    return [] if not listXS else listXS[-1:] + reverseList(listXS[:-1])

If you wanted an inplace solution:

def reverseList(listXS, i=1):
    if i == len(listXS) - 1:
        return
    listXS[i-1], listXS[-i] = listXS[-i], listXS[i-1]
    reverseList(listXS, i+1)

reversing the original list:

In [22]: l = [1, 2, 3, 4,5]  
In [23]: reverseList(l)    
In [24]: l
Out[24]: [5, 4, 3, 2, 1]    
In [25]: l = [1, 2, 3, 4]    
In [26]: reverseList(l)    
In [27]: l
Out[27]: [4, 3, 2, 1]
like image 132
Padraic Cunningham Avatar answered Sep 05 '26 06:09

Padraic Cunningham


There is a function for this:

>>> [1,2,3,4,5].reverse()
[5,4,3,2,1]
like image 44
Colby Gallup Avatar answered Sep 05 '26 04:09

Colby Gallup



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!