Question on code for Range(start, end, increment)


#1



Hey guys - I have the answer on this already but looking for an explanation as to how range works in this instance:
I understand that it is starting point, ending point and increments. However, if I do the below it doesn't make sense:

print len("cheese") #this equals 6
Therefore when using range, how come when I start at range(len(text)-1, -1, -1) it doesn't start at S and starts at E? Also, why is it not 0 where I want it to finish instead of -1? The increment -1 I understand :slight_smile: Just trying to grasp it - thanks in advance


def reverse(text):
    backwards = []
    text = str(text)
    i = len(text)
    for l in range(len(text)-1, -1, -1):
        backwards.append(text[l])
    return "".join(backwards)


#2

The range function works like this: range([start], stop, [step])
if text = "cheese", then len(text) is equal to 6. Python in general is 0-index based, meaning list indexes start at 0, not 1.

The last integer generated by range() is up to, but not including, stop. For example range(0, 5) generates integers from 0 up to, but not including, 5. So if you wanted to include 0, you gotta put -1.

I consulted this site here.


#3

That is great - thank you for your explanation I have noted it in my notepad!
Appreciate it


#4

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