1

I'm trying to understand Generators and have come across the following code:

def reverse(data):
    for index in range(len(data)-1, -1, -1):
        yield data[index]


for s in reverse([1,2,3]):
    print s

I understand that we start at index 2, decrement by 1 and end at -1. What I don't get is the fact that the stopping point -1 ,I thought, should refer to "3", but it appears to refer to "1" here? :

3
2
1

Thanks

2
  • 1
    check the output of range(len(data)-1, -1, -1) before assuming anything about the stopping point (especially since the evidence point against your assumption) Commented Oct 1, 2014 at 22:13
  • 1
    range actually stops before the upper limit. Presumably it behaves this way to ensure for i in range(3) will iterate 3 times as most people would expect, with i taking on the values [0, 1, 2]. In your case, range(2, -1, -1) outputs [2, 1, 0], which corresponds to the indices of the output you're seeing. Commented Oct 1, 2014 at 22:16

1 Answer 1

1

Please see https://docs.python.org/2/library/functions.html#range to see how range works. I can see it may be initially confusing to read the documentation but hope my explanation below, for your case, helps.

Specifically these lines from the above doc answers your question: ' The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop'

In your case start=2(len(data)-1), stop =-l and step=-1. So the potential list of integers would be [2, 2-1, 2-2*1, 2-3*1 ...] which is [2,1,0,-1 ...]. However since your step is negative, i.e, -1, the last element would be smallest (start + i*step) greater than stop. In the potential list, the smallest item greater than stop, i.e greater than -1 is 0. So range(len(data)-1, -1, -1) returns [2,1,0]

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

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.