DocsHub
Animations

Reverse a String — Visual Walkthrough

Watch how each character gets prepended to the front of the result, building the reversed string step by step.

Reverse a String

Input: "PYTHON"

Loop through every character and add it to the front of the result. The first character ends up last — the last character ends up first.

Reverse Stringprepend · O(n)
inputPYTHON

Input string

P
[0]
Y
[1]
T
[2]
H
[3]
O
[4]
N
[5]

result (building from front)

0 / 6 chars
empty string ""
reverse_string.py
def reverse_string(s):
result = ""
for char in s:
# pick current character
result = char + result # prepend
return result
Call reverse_string("PYTHON")
step 0/15
0%

How it works

def reverse_string(s):
    result = ""

    for char in s:
        result = char + result  # prepend to front

    return result

Each iteration — the new character goes to the front, pushing everything already in result one position to the right.

Stepcharresult
1P"P"
2Y"YP"
3T"TYP"
4H"HTYP"
5O"OHTYP"
6N"NOHTYP"

The cleanest Python solution is s[::-1] — slice with step -1. The loop version shown here is more useful for understanding what reversal actually does step by step.

Complexity

TimeSpace
This approachO(n)O(n)

On this page