Python for loop decrementing index
In this tutorial, let’s look at for loop of decrementing index in Python.
A for loop in python is used to iterate over elements of a sequence. It is mostly used when a code has to be repeated ‘n’ number of times. In general, for loop in python is auto-incremented by 1. What if you want to decrement the index. This can be done by using “range” function. Let’s look at it in detail.
Range Function in Python
Range function returns a new list of numbers within the specified range. Note that Range() function can be used for only for integers.
Example of simple range function:
for x in range(3): print(x)
0 1 2
Here, all the numbers from 0(zero) till the specified range(i.e. 3 here) are printed.
What if we want to start the loop from some other number rather than zero, then we can use the range function as shown below.
Syntax for range:
range(start index, stop index, step)
Here, start and step are optional arguments. As seen in previous example only stop value is given and it starts from 0(by default) also its step is 1(by default)
Decrementing the index value in Python
If the user wants to decrement the index value inside for loop then he/she should make the step value negative. By making the step value negative it is possible to decrement the loop counter.
for x in range(10,0,-2): print(x)
10 8 6 4 2
As it is observed, initial value of x is 10 and it goes on decrementing till 0 with the step value -2.
- In for loop, index is by default incremented by 1.
- To decrement the index in for loop, make the step value negative.
Hope you got an idea on the topic “Decrementing index in for loop in Python”