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))
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]
There is a function for this:
>>> [1,2,3,4,5].reverse()
[5,4,3,2,1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With