How to Reverse a List Using Recursion in Python?

Estimated read time 1 min read

You can reverse a list using recursion in Python by defining a recursive function that takes a list and returns a reversed list. Here’s an example:

def reverse_list_recursive(lst):
    if len(lst) == 0:
        return []
        return [lst[-1]] + reverse_list_recursive(lst[:-1])

In this function, if the length of the list is zero, it returns an empty list. Otherwise, it returns a new list that is created by concatenating the last element of the list with the result of recursively calling the function on the rest of the list (excluding the last element).

Here’s an example of how to use this function:

my_list = [1, 2, 3, 4, 5]
reversed_list = reverse_list_recursive(my_list)
print(reversed_list) # Output: [5, 4, 3, 2, 1]

Note that this method can be less efficient than using the built-in reverse() method or a loop for large lists due to the overhead of function calls and stack usage.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply