def rreverse(s):
    if s == "":
        return s
    else:
        return rreverse(s[1:]) + s[0]

(Very few people do heavy recursive processing in Python, the language wasn't designed for it.)

Answer from Fred Foo on Stack Overflow
Top answer
1 of 8
39
def rreverse(s):
    if s == "":
        return s
    else:
        return rreverse(s[1:]) + s[0]

(Very few people do heavy recursive processing in Python, the language wasn't designed for it.)

2 of 8
37

To solve a problem recursively, find a trivial case that is easy to solve, and figure out how to get to that trivial case by breaking the problem down into simpler and simpler versions of itself.

What is the first thing you do in reversing a string? Literally the first thing? You get the last character of the string, right?

So the reverse of a string is the last character, followed by the reverse of everything but the last character, which is where the recursion comes in. The last character of a string can be written as x[-1] while everything but the last character is x[:-1].

Now, how do you "bottom out"? That is, what is the trivial case you can solve without recursion? One answer is the one-character string, which is the same forward and reversed. So if you get a one-character string, you are done.

But the empty string is even more trivial, and someone might actually pass that in to your function, so we should probably use that instead. A one-character string can, after all, also be broken down into the last character and everything but the last character; it's just that everything but the last character is the empty string. So if we handle the empty string by just returning it, we're set.

Put it all together and you get:

def backward(text):
    if text == "":
        return text
    else:
        return text[-1] + backward(text[:-1])

Or in one line:

backward = lambda t: t[-1] + backward(t[:-1]) if t else t

As others have pointed out, this is not the way you would usually do this in Python. An iterative solution is going to be faster, and using slicing to do it is going to be faster still.

Additionally, Python imposes a limit on stack size, and there's no tail call optimization, so a recursive solution would be limited to reversing strings of only about a thousand characters. You can increase Python's stack size, but there would still be a fixed limit, while other solutions can always handle a string of any length.

๐ŸŒ
Medium
medium.com โ€บ @fridahwatetu โ€บ reversing-a-string-in-python-using-recursion-21346d959f68
Reversing a String In Python Using Recursion | by Fridah | Medium
August 8, 2023 - Reversing a String In Python Using Recursion string = "Hello World" def reversing_string(string): if (string == ""): return "" return reversing_string(string[1:]) + string[0] str โ€ฆ
Discussions

Reversing a String in Python Recursively - Stack Overflow
For a homework assignment I have to create a recursive function that reverses a string. Here's what I have currently. The last three lines of code were made by the instructor and we aren't allowed to More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to reverse a string using recursion? - Stack Overflow
I'm trying out a simple program which would allow me to print out the reverse word of "computer". When I run my code, I received a runtime error RuntimeError: maximum recursion depth exceeded in c... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Trying to reverse a string using recursion, why is my program not working?
If you are trying to do recursion then you want to have a return. Each step in the recursive process should do one unit of work. After the one unit of work is done, it should examine the data to see if it's done. If it is done, return. If it isn't done recurse. Here's an example in PHP: public function reverseString($input) { // Get the last character in the list/array/string $last_char = $input[strlen($input) - 1]; // Compute the remaining list/array/string $new_input = substr($input, 0, -1); // If the new list/array/string is empty, we are done so we return our result // Else return our result concatenated with the next result if (strlen($new_input) == 0) { return $last_char; } else { return $last_char . $this->reverseString($new_input); } } More on reddit.com
๐ŸŒ r/AskComputerScience
17
16
February 28, 2020
python - Reversing a string recursively? - Stack Overflow
As you can see, I really struggle with recursive. Any assistance you can give me on this would be much appreciated. Thank you! ... [1, 2, 3, 4, 5] is a list and its reverse is not 5 1 2 3 4. Even if its a string its revers still is not 5 1 2 3 4 it'd be "]5, 4, 3, 2, 1[". More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ dsa โ€บ reverse-a-string-using-recursion
Print reverse of a string using recursion - GeeksforGeeks
March 6, 2025 - Input: s = "Reverse a string Using Recursion" Output: "noisruceR gnisU gnirts a esreveR" Explanation: After reversing the input string we get "noisruceR gnisU gnirts a esreveR".
๐ŸŒ
Sanfoundry
sanfoundry.com โ€บ python-program-reverse-string-using-recursion
Reverse a String in Python - Sanfoundry
June 19, 2023 - In this approach, we use recursion to reverse a string by repeatedly swapping the first and last characters. ... Here is source code of the Python Program to reverse a string using recursion.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-reverse-string-string-reversal-in-python-explained-with-code-examples
Python Reverse String โ€“ String Reversal in Python Explained with Examples
November 10, 2021 - But since Python strings are immutable, you cannot modify or reverse them in place. In Python, there are a few different ways you can do this. And this tutorial will teach you how you can use string slicing, built-in methods, and recursion to reverse strings.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ python-program-to-reverse-a-string-using-recursion
Python Program to Reverse a String Using Recursion
When it is required to reverse a string using recursion technique, a user-defined method is used along with recursion. The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger
๐ŸŒ
GitHub
github.com โ€บ arnab132 โ€บ Reverse-String-using-Recursion-in-Python
GitHub - arnab132/Reverse-String-using-Recursion-in-Python: Implementation of Reverse String using Recursion in Python ยท GitHub
If not equal to 0, the reverse function is recursively called to slice the part of the string except the first character and concatenate the first character to the end of the sliced string.
Author ย  arnab132
Find elsewhere
๐ŸŒ
Flexiple
flexiple.com โ€บ python โ€บ python-reverse-string
Reverse String In Python - Flexiple
March 18, 2024 - To reverse a string in Python using recursion, employ a function that recursively chops off the first character and appends it to the end.
๐ŸŒ
YouTube
youtube.com โ€บ watch
Reverse The Given String Using Recursion | Python Programs | Interview Question And Answer - YouTube
In this Python programming video series we will learn how to reverse the given string using recursion.Program 01:def reverse_str(str1): if str1 == "": ...
Published ย  February 1, 2021
๐ŸŒ
Career Karma
careerkarma.com โ€บ blog โ€บ python โ€บ python reverse string: a step-by-step guide
Python Reverse String: A Step-By-Step Guide | Career Karma
December 1, 2023 - You can reverse a string in Python using slicing or the reversed() method. A recursive function that reads each character in a string and reverses the entire string is another common way to reverse a string.
๐ŸŒ
BeginnersBook -
beginnersbook.com โ€บ home โ€บ python examples โ€บ python program to reverse a string using recursion
Python program to reverse a String using Recursion
June 6, 2018 - # Program published on https://beginnersbook.com # Python program to reverse a given String # Using Recursion # user-defined recursive function def reverse(str): if len(str) == 0: return str else: return reverse(str[1:]) + str[0] mystr = "BeginnersBook" print("The Given String is: ", mystr) ...
๐ŸŒ
Real Python
realpython.com โ€บ reverse-string-python
Reverse Strings in Python: reversed(), Slicing, and More โ€“ Real Python
July 31, 2023 - Here, you first compute the index of the last character in the input string by using len(). The loop iterates from index down to and including 0. In every iteration, you use the augmented assignment operator (+=) to create an intermediate string that concatenates the content of result with the corresponding character from text. Again, the final result is a new string that results from reversing the input string. ... You can also use recursion to reverse strings.
๐ŸŒ
CodingBroz
codingbroz.com โ€บ home โ€บ python โ€บ python program to reverse a string using recursion
Python Program to Reverse a String Using Recursion - CodingBroz
November 27, 2021 - def reverse(string): if len(string) == 0: return string else: return reverse(string[1:]) + string[0] We have declared a recursive function named reverse.
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ string reverse in python
Reverse String in Python - Scaler Topics
April 8, 2022 - After iterating in reverse order, ... to reverse the string. We will recursively call the reverse() function and keep adding the last index character to the starting of the string....
๐ŸŒ
Reddit
reddit.com โ€บ r/askcomputerscience โ€บ trying to reverse a string using recursion, why is my program not working?
Trying to reverse a string using recursion, why is my program not working? : r/AskComputerScience
February 28, 2020 - I'm also not sure if the O(1) recursive like solution works in python because, as far as I know, python does not support tail call optimization. ... class Solution { public: void reverseString(vector<char>& s) { reverse(s, 0, s.size() - 1); } void reverse(vector<char>& s,int left,int right){ // stop when all characters have been swapped if(left> right){ return; } // swap first and last unreversed characters char temp = s[left]; s[left] = s[right]; s[right] = temp; // call the function on the next unreversed characters reverse(s, left + 1, right - 1); } };
๐ŸŒ
Linode
linode.com โ€บ docs โ€บ guides โ€บ how-to-reverse-a-string-in-python
How to Reverse a String in Python | Linode Docs
May 13, 2022 - Working back from the deepest recursion ... the new reversing_string. For the example string, the process of this working back looks something like this: "f" + "l" + "o" + "w" + " " + "m" + "o" + "o" + "d" While not the fastest of the approaches covered in this guide, the recursive function has the advantage of following functional programming principles. ... The Python interpreter ...
Top answer
1 of 3
5

They are not adding up immediately until recursion reaches to final expression. Here, what is happening on each step:

"5" + backwards("1234")
"5" + "4" + backwards("123")
"5" + "4" + "3" + backwards("12")
"5" + "4" + "3" + "2" + backwards("1")
"5" + "4" + "3" + "2" + "1" + backwards("")
"5" + "4" + "3" + "2" + "1" + ""
"54321"

Basically you are constructing a chain of return statements (aka call stack), they concatenate at the very end into "54321".

In above computation, I omitted return keywords. For e.g. "5" + "4" + backwards("123") looks like return "5" + (return "4" + backwards("123")) in reality.

2 of 3
1

You are correct in what text[-1] and text[:-1] give you. I think where you're getting tripped up is on the recursive aspect of it, which is the tricky part.

When you're working on recursive stuff it helps not to overthink it. I know that most of programming requires you to understand every little nuance of your code but recursion is different. If you try to think through a recursive function's call stack in your head you'll just get confused. Human brains aren't like computers. Our stacks can only get about three levels deep before we lose track.

So for this problem the way you want to think about it is something like this:

"To reverse a string, you simply take the last character and put it at the beginning of the reversified version of the remaining characters."

It seems like a nonsense statement because it's defined in terms of itself, but that's precisely what recursion is, a function that is defined in terms of itself.

So for you question, text[-1] gives you the last item in the list and text[:-1] give you the remaining characters.

As an example, if your list is [1, 2, 3, 4] then evaluating each recursive call would go something like this:

backwards([1, 2, 3, 4])

evaluates to

4 + backwards([1, 2, 3])

which evaluates to

4 + 3 + backwards[1, 2])

which evaluates to

4 + 3 + 2 + backwards([1])

which evaluates to

4 + 3 + 2 + 1

When I first answered this question, I thought the function you listed didn't work and you wanted one that did, so I threw one together real quick. When I wrote it, I literally typed out the quote I listed above into my text editor then wrote out the python code (which looks just like the one you have posted). I didn't step through each call in my head I just typed out the sentence then wrote some code that implemented that sentence.

Recursion takes some getting used to but once you kind of get how think recursively you can apply it to all kinds of problems.

Another example that might be a bit more straight forward would be a recursive function that sums up all the numbers in a list.

sum([1, 2, 3, 4]) => 10

So the statement for this would be

To sum a list, add the first item in the list to the sum of the remaining elements in the list.

The python would look like this:

def sum(a):
    if len(a) == 0:
        return 0
    else:
        return a[0] + sum(a[1:])