0

I have the following function:

s = 'hello'
rev = ''

for char in s:
    rev = char + rev
return rev

Why does the for loop above add the characters in reverse? I tried using rev += char and it returned the string in the original order, s. This was mentioned in a video and they didn't explain properly, just said "Python's for loop over string doesn't work that way". I want to know why it does this, so in the future I will be more inclined to avoid these mistakes.

Another question is, can I implement this type of line in the for-loop over lists and will it output the reverse of the list? Since lists are mutable.

7
  • 1
    Because you're adding the character the the beginning of the list. Do rev = rev + char or simply rev += char (which means the same thing) instead. Commented Nov 2, 2019 at 1:03
  • 2
    Surely the purpose of this code is to reverse the string? Otherwise you would just return s directly. Commented Nov 2, 2019 at 1:05
  • This has nothing to do with "Python's for loop over string doesn't work that way". It's just because you are doing rev = ch + rev, that is: iterating over every character and adding it at the beginning of rev. Commented Nov 2, 2019 at 1:05
  • On the first iteration you have rev = "h" + "" so rev is set to "h". Then you have rev = "e" + "h" so rev is set to "eh" then you have rev = "l" + "eh" and rev becomes "leh" and so on. Commented Nov 2, 2019 at 1:08
  • Also, if you want to reverse the order, use string slicing 'hello'[::-1] = 'olleh'. See Strings and Character Data in Python. ['t', 'e', 's', 't'][::-1] = ['t', 's', 'e', 't'] lists too. Commented Nov 2, 2019 at 1:08

2 Answers 2

3

The +-operator on strings means concatenation which is not commutative. So there's a difference between char + rev and rev + char.

Successively prepending the next character in front effectively reverses the string.

Sign up to request clarification or add additional context in comments.

Comments

1

In the loop you have, your for loop is defined as:

s = 'happy'
rev = ''

for char in s:
    rev = ch + rev

If we look at this going through the first few iterations, we would get: h ah pah ppah yppah

This is because as you update the variable rev, you are adding the next character (char) in front of rev through your definition.

rev = NEW CHARACTER + CURRENT REV so looking at the final iteration, where we add y, you're adding:

rev = NEW CHARACTER (Y) + CURRENT REV (PPAH), basically stating you are adding PPAH to the letter y, instead of adding y to PPAH.

The loop can be easily fixed by swapping ch and rev, making it:

for char in s:
    rev = rev + char

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.