Reputation: 7879
My professor posted the function below. I do not fully understand how it's working. Could someone explain it?
def rev(a):
if a == []:
return []
else:
return rev(a[1:]) + [a[0]]
Upvotes: 0
Views: 85
Reputation: 88977
What this does is recursively reverses a list. The easiest way to see how it works is to follow through the execution.
The function takes the string and solves it by returning the reversed version of all but the first item (a[1:]
) with the first item appended to the end.
Note that this is a bad way to do this in a real situation (I am presuming your professor is just showing the idea of recursion), as Python isn't optimized for recursion. Instead, use the reversed()
builtin.
Also, it isn't particularly Pythonic code. If one had to have a recursive solution, instead of using the efficient, effective, well-tested, easy-to-use built-in, consider:
def rev(seq):
return rev(seq[1:]) + [seq[0]] if seq else []
if/else
. a
with seq
makes the function clearer - Python doesn't have strict typing, so using names that give a clue to what the function takes (in this case, a sequence), makes it clearer.a == []
by simply checking seq
. As lists evaluate to False
when empty, there is no need to compare to an empty list.Upvotes: 2
Reputation: 26333
a is a list. If a is the empty list, you return the empty list. If not, you apply (recursively) your 'reverse' function to the list but the first element, and you append the first element. This way, at each recursive call for reverse, you build your reversed list beginning with its rightmost element.
This is an example:
l=[1,4,6,7]
rev(l) returns rev([4,6,7])+[1]
rev([4,6,7]) returns rev([6,7])+[4]
...
and in the end you have rev([]) returning the empty list and terminating the recursive calls.
BTW, to reverse a list l
, just use
l[::-1]
Upvotes: 2