Open In App

How to Decrement a Python for Loop

Last Updated : 29 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python’s for loop is a fundamental construct used for iterating over sequences. While Python does not have a built-in feature to decrement a loop index directly, there are multiple approaches to achieve this functionality. In this article, we’ll explore different methods to decrement a for loop in Python, each with its advantages and use cases.

Decrement a For Loop in Python

Below are some of the ways by which we can decrement a for loop in Python:

  1. Using the reversed() Function
  2. Iterating Over a Reversed Range
  3. Decrementing the Loop Index Manually

Decrement a For Loop Using the reversed() Function

In this example, the reversed() function is used with range(5) to create an iterator that yields values from 4 to 0. The for loop then iterates over these values, printing each one in reverse order.

Python3
for i in reversed(range(5)):
    print(i)

Output
4
3
2
1
0

Decrement a For Loop Using Negative Step Value

In this example, the range(4, -1, -1) function generates a sequence starting from 4 and decrementing by 1 until reaching -1 (exclusive). The for loop iterates over this sequence, printing each value in reverse order.

Python3
for i in range(4, -1, -1):
    print(i)

Output
4
3
2
1
0

Decrement a For Loop By Decrementing the Loop Index Manually

In this example, the code iterates over the indices of “my_list” in reverse order using a for loop. The elements of “my_list” are printed in reverse order by accessing them with reverse indices.

Python3
my_list = [1, 2, 3, 4, 5]
length = len(my_list)

for i in range(length):
    index = length - i - 1
    print(my_list[index])

Output
5
4
3
2
1

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads