Good day. I don’t entirely understand this code.
I understand that the syntax for range is range(start, stop, step/stride)
. And that the default arguments are range(start = 0, stop=, step= 1)
, so what I understand from your code is:
for i in range(len(list) - 1, -1, -1):
is that the index (i)
should start at len(lst) - 1
, because you want to start at the index of end of the list, which would be len(list) - 1
, because in a list of 10 elements it would be index 9, as index starts from zero.
I also understand the step/stride portion, because we want i
to iterate backwards from the last index.
But what I do not understand is why the end argument is -1
, which is at the end of the list. Since we are iterating backwards, shouldn't it end at the start of the list, which should be zero? That is the portion I don’t understand. Please can you shed more light on this?
Sorry to bother you again but I also don’t fully understand the list slice.
I know the syntax for list slicing is list[start : stop : step]
, I understand the step or stride portion and I know the default arguments are list[start= 0 : stop = -1 and step =1]
. I understand the step part since we want to iterate backwards when using list[: : -1]
.
What I don’t understand, is how python knows to start at the end of the list since the default argument is still -1
or is it because 0-1=-1
so it starts from the end?
Furthermore, how does it know to end at the beginning rather than at -1
, which is the default argument?
Thank you very much.