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]]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
if/else.awithseqmakes 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 checkingseq. As lists evaluate toFalsewhen empty, there is no need to compare to an empty list.