0
def reverse(x):
    output = ""
    for c in x:
        output = c + output

    return output

print(reverse("Hello"))

This code works fine to reverse a string in Python, I just can't seem to understand why it is working and how.

If, for example, I iterate through a string, usually it will iterate and print starting from "H" and work its way down to "O." How is it that here, it's going backwards?

2
  • The key is in output = c + output. The character is concatenated to the beginning of the output string instead of to the end, resulting in a reversed string. The easiest way to reverse a string, however, is x[::-1]. Commented Jun 27, 2019 at 19:06
  • I would suggest using this site - python tutor - for this kind of problems. Simply copy your code there and you can visualize it step by step! Very helpful to understand small programs like this :) Commented Jun 27, 2019 at 21:16

3 Answers 3

2

If you put some output to your loop you can see how the code is filling up the string.

def reverse(x):
    output = ""
    for c in x:
        output = c + output
        print(output)

    return output

print(reverse("Hello"))

So you can see how it works:

H
eH
leH
lleH
olleH
olleH

So you ad the last one to the end and that is how you reverse it. If you switch the following line in your loop:

output = output + c 

Then the order is not reversed:

H
He
Hel
Hell
Hello
Hello
Sign up to request clarification or add additional context in comments.

Comments

1

This loop goes over the characters of the string, and for each character prepends it to the current result.

Let's track the value of output as we go over the characters (the c values):

c output
H H
e eH
l leH
l lleH
o olleH

Comments

0

Every time a character goes into the loop, it gets appended into the output. Initially output = ""

So for iteration 1: output = ""

c = "H"
output = "H" + "" = "H"

Iteration 2: output = "H"

c = "e"
output = "e" + "H" = "eH"

Iteration 3: output = "eH"

c = "l"
output = "l" + "eH" = "leH"

Iteration 4: output = "leH"

c = "l"
output = "l" + "leH" = "lleH"

Iteration 5: output = "lleH"

c = "o"
output = "o" + "lleH" = "olleH"

So the final result comes out to "olleH"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.