def revlist(lst):
if len(lst) == 1:
return lst
else:
return lst[(len(lst) - 1)
I have come as far as this but I don't know what to do next. I'm practicing recursion for my exams. If anyone could help I'd be grateful.
In order to reverse a list without using the built-in reverse() function, we use the Slicing Operator. The slicing operator is another method used for reversing the data elements.
You can reverse a list in Python using the built-in reverse() or reversed() methods. These methods will reverse the list without creating a new list. Python reverse() and reversed() will reverse the elements in the original list object. Reversing a list is a common part of any programming language.
Python comes with a number of methods and functions that allow you to reverse a list, either directly or by iterating over the list object. You'll learn how to reverse a Python list by using the reversed() function, the . reverse() method, list indexing, for loops, list comprehensions, and the slice method.
Your simple case is fine, if the length of the list is 1 (or smaller), simply return the list. In fact, we can simply check whether the list is empty (by issueing if not lst
). If the list is larger, you have to think about how to simplify the problem in the recursive case.
In words, you can formulate it like this:
If the list is longer than 1, give me the last element of that list extended by the list I get when I reverse the given list without the last element in it. The latter list is one smaller than the original list, thus the problem is simplified.
In code:
def reverse(lst):
if not lst: # this will be true if lst == []
return lst
return lst[-1:] + reverse(lst[:-1]) # recursive case
# Demo
print(reverse([1,2,3,4,5])) # [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