Practice makes perfect (REVERSE),I passed but still confused


I passed this section but still I am confused, CAN ANYONE EXPLAIN ME PLEASE.

Suppose the text is " PYTHON"
In my code if I put this [for i in range (n, -1, -1) ]. It shows error. I did this because nth item is "N" so the new word will start from "N". Why is this incorrect?

But, in my code [ for i in range (n-1, -1, -1) ]. It means that counting starts from n-1 and ends at -1. The (n-1)th item in the word Python is "O", that means it should start from "O". I think this code should print "OHTYP" but it says correct. How is this correct???
Am I missing something. please help.

Can anyone please explain me this? Thanks in advance.

def reverse(text):
    n = len(text)
    x = ""
    for i in range(n-1, -1, -1):
        x = x + text[i]
    return x


Consider that when n is len(text), the nth index position is undefined. N is at n-1.


Let's consider this code:

text = "Python"
n = len(text)
print range(n-1, -1, -1)

it outputs:

[5, 4, 3, 2, 1, 0]

To understand why it outputs this code you have to know meaning of all the range(start, stop, step) parameters:

  • start -> starting number of the sequence
  • stop -> numbers will be generated up to value of this parameter, but not including this number
  • step -> difference between elements of the sequence

So the resulting list of indices will start from n - 1, where n is a length of the text (we start indexing from 0, so the last element has index n - 1). List will go up to -1, but not including. And the difference between values of the list will be equal -1.


factoradic, thank you very much . Now I got it. Thank you.


You're very welcome :slight_smile:


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.