How do I reverse a list using recursion in Python?
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?
Append the first element of the list to a reversed sublist:
mylist = [1, 2, 3, 4, 5]
backwards = lambda l: (backwards (l[1:]) + l[:1] if l else [])
print backwards (mylist)
A bit more explicit:
def rev(l):
if len(l) == 0: return []
return [l[-1]] + rev(l[:-1])
This turns into:
def rev(l):
if not l: return []
return [l[-1]] + rev(l[:-1])
Which turns into:
def rev(l):
return [l[-1]] + rev(l[:-1]) if l else []
Which is the same as another answer.
Tail recursive / CPS style (which python doesn't optimize for anyway):
def rev(l, k):
if len(l) == 0: return k([])
def b(res):
return k([l[-1]] + res)
return rev(l[:-1],b)
>>> rev([1, 2, 3, 4, 5], lambda x: x)
[5, 4, 3, 2, 1]
I know it's not a helpful answer (though this question has been already answered), but in any real code, please don't do that. Python cannot optimize tail-calls, has slow function calls and has a fixed recursion depth, so there are at least 3 reasons why to do it iteratively instead.
The trick is to join after recursing:
def backwards(l): if not l: return x, y = l[0], l[1:] return backwards(y) + [x]
Use the Divide & conquer strategy. D&C algorithms are recursive algorithms. To solve this problem using D&C, there are two steps:
- Figure out the base case. This should be the simplest possible case.
- Divide or decrease your problem until it becomes the base case.
Step 1: Figure out the base case. What’s the simplest list you could get? If you get an list with 0 or 1 element, that’s pretty easy to sum up.
if len(l) == 0: #base case
return []
Step 2: You need to move closer to an empty list with every recursive call
recursive(l) #recursion case
for example
l = [1,2,4,6]
def recursive(l):
if len(l) == 0:
return [] # base case
else:
return [l.pop()] + recursive(l) # recusrive case
print recursive(l)
>[6,4,2,1]
Source : Grokking Algorithms