Jika Jika - 3 months ago 19
Python Question

How to count down in for loop?

In Java, I have the following for loop and I am learning Python:

for (int index = last-1; index >= posn; index--)

My question is simple and probably obvious for most of people who are familiar with Python. I would like to code that 'for' loop in Python. How can I do this?

I tried to do the following:

for index in range(last-1, posn, -1):

I think it should be
range(last-1, posn + 1, -1)
. Am I right?

I am thankful to anyone especially who will explain to me how to understand the indices work in Python.


The range function in python has the syntax:

range(start, end, step)

It has the same syntax as python lists where the start is inclusive but the end is exclusive.

So if you want to count from 5 to 1, you would use range(5,0,-1) and if you wanted to count from last to posn you would use range(last, posn - 1, -1).