Practice Makes Perfect: reverse. Why does code work?


Practice Makes Perfect: reverse

My code works, but I don't understand why range(len(text)-1, -1, -1) works. How does repeating -1 three times produce the correct range?

Thanks for the help!

def reverse(text):
    new_word = ''
    for char in range(len(text) -1, -1, -1):
        new_word += text[char]
    return new_word


Without passing judgement, the first rule of coding is to never use code we do not understand.

To understand how this code works we need to examine the range() function. It returns an iterable given a start index, a stop index, and a step interval.

We wish this range to iterate from the last to the first letter in text, so the start index will be,

len(text) - 1

since the last index is always one less than the length.

The stop index given in the range argument is exclusive meaning it is not included in the range iterator. We need the stop index to be 0 since that is the index of the first letter in text. Since the stop is not included, we must proceed one more to the left of zero, hence, - 1.

The step takes its direction from the sign on the given interval. A negative sign means right to left.

range(len(text) - 1, -1, -1)

Iterates from the last to the first, working from right to left.


Great! Thank you! For some reason, it's so hard to wrap my head around this concept - but your explanation helps a lot!


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