Reverse Range in Python | Print Second Element in Decreasing Order

Reverse Range in Python | Print Second Element in Decreasing Order

Most of the time, we use the range() method in the for-loop.

Built-in function range() is used to get the sequence of elements. We have already learned about the range() method and its syntax.

range() syntax:

range(start, stop, step)

Here we want to get the range in decreasing order using for-loop in Python.

Print Reverse Range in Python using for-loop

How to print numbers in reverse Order in Python using for-loop?

Method 1: Using step

If you set the step value to -1, for-loop print the value in reverse order.

for i in range(10, 1, -1):
  print(i)

Output:

10
9
8
7
6
5
4
3
2

Method 2: Using reversed()

reversed() is the built-in method that returns the sequence in reverse order.

for i in reversed(range(2, 11)):
  print(i)

Output:

10
9
8
7
6
5
4
3
2

If you need to print the element in the reverse method, I would recommend using the first method. Using reversed() method adds extra computation. So in terms of performance, avoid using reversed() method.

Just another example.

Print every second element in decreasing order from the given range in Python.

for i in range(10, 1, -2):
  print(i)

Output:

10
8
6
4
2

This is all about this tutorial to reverse range in Python. Any doubts? Let me know in the comment.

Leave a Reply

Your email address will not be published. Required fields are marked *