2

I want to reverse a string like so:

def reverse(s):
    for i in range(len(s),0,-1):
        var = s[i] # getting an out of range error?
        ... 

Can someone explain why?

5
  • 6
    len(s) == N, s[N] is out of bounds, the last valid index is N-1 Commented Oct 22, 2015 at 9:10
  • 1
    do for i in range(len(s)-1,-1,-1) instead Commented Oct 22, 2015 at 9:12
  • Thank you guys for the quick responses! I understand now :) Commented Oct 22, 2015 at 9:15
  • 1
    I find reversed(range(len(s))) more readable than range(len(s)-1,-1,-1) Commented Oct 22, 2015 at 9:19
  • 1
    FYI there is a easier way s[::-1] would also reverse the string. Commented Oct 22, 2015 at 9:43

2 Answers 2

3

If a string length is n, the valid indexes are from 0 to n-1 (the elements are counted from 0 not from 1).

In your code the for loop condition len(s) should be changed into len(s) - 1.

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

1 Comment

Thank you for a quick and simple answer! Will accept the answer in 7 minutes.
1

simplicis's answer is so good, but here is an easy way to reverse a string like this:

print('Hello'[::-1])

Output:

olleH

2 Comments

Thanks for the response as well! I'm doing a Codecademy tutorial, and they specifically instructed not to use it that way ;) but I appreciate it!
Okay, just a tip. If you want to reverse a string, this is the best way :P

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.