close

How to count down in for loop?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to count down in for loop in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to count down in for loop?

  1. How to count down in for loop?

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

  2. count down in for loop

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

Method 1

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

Method 2


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)

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read