0

I'm a python beginner and I am learning to reverse a list without using [::-1] and the reversed function. I read this explanation below but wasn't sure how the principle works. Are -1,-1,-1 in range(len(list)-1, -1, -1) working like the start, stop, step in index? If it is, why is the second number -1 as well? I'm posting this as I know no one to ask about coding.

https://stackoverflow.com/a/530507/17098889

yopangyo
  • 29
  • 2
  • 2
    See the [relevant documentation](https://docs.python.org/3/library/stdtypes.html#typesseq-range) – juanpa.arrivillaga Oct 21 '21 at 17:50
  • 2
    The linked answer has it all: *"...it's basically saying: start with 1 less than len(collection), keep going until you get to just before -1, by steps of -1."*. – trincot Oct 21 '21 at 18:04
  • Thanks! But why is it going until you get just before -1? I'm sorry to ask several times but it's kind of confusing – yopangyo Oct 21 '21 at 18:13
  • The range syntax is basically `range(start, stop, step)`, where the `start` index is inclusive but the `stop` index is not. Similar logic to range = [start, stop) if you know what I mean. So, `range(50,-1,-1)` would mean starting from 50, keep decrementing by 1 till you reach 0 (an integer just greater than -1 since -1 is not included) – tidakdiinginkan Oct 21 '21 at 18:13
  • for eg: `range(7,5,-1)` = `[7,6]` (meaning start from 7, decrement by 1 and go up to (5+1)) – tidakdiinginkan Oct 21 '21 at 18:15
  • ah, thank you!:) Now I understood. So the reason why the start index starts as len(collection)-1 is that if you do not decrement 1, you would get 1, not a 0 as the last number for the result. Am I correct? – yopangyo Oct 21 '21 at 18:20
  • I mean index 1 and index 0! – yopangyo Oct 21 '21 at 18:23

0 Answers0