Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count down in for loop? [duplicate]

Tags:

python

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.

like image 642
Jika Avatar asked Mar 27 '15 02:03

Jika


People also ask

How do you count backwards in Python?

How to reverse a range in Python. To reverse a range of numbers in Python with the range() function, you use a negative step, like -1 .


2 Answers

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).

like image 157
Loocid Avatar answered Oct 04 '22 05:10

Loocid


In python, when you have an iterable, usually you iterate without an index:

letters = 'abcdef' # or a list, tupple or other iterable for l in letters:     print(l) 

If you need to traverse the iterable in reverse order, you would do:

for l in letters[::-1]:     print(l) 

When for any reason you need the index, you can use enumerate:

for i, l in enumerate(letters, start=1): #start is 0 by default     print(i,l) 

You can enumerate in reverse order too...

for i, l in enumerate(letters[::-1])     print(i,l) 

ON ANOTHER NOTE...

Usually when we traverse an iterable we do it to apply the same procedure or function to each element. In these cases, it is better to use map:

If we need to capitilize each letter:

map(str.upper, letters) 

Or get the Unicode code of each letter:

map(ord, letters) 
like image 43
chapelo Avatar answered Oct 04 '22 05:10

chapelo