How to reverse a range in Python?
In this short tutorial, we look at how you could use Python to range reverse. We also look at the range() methods with examples.Table of Contents - Python range reverse
- Python range()
- Syntax
- Code and Explanation
- Reversing a range in Python
- Closing thoughts
- Other Related Concepts
Python range():
The range() function allows you to generate a list of numbers within a specified range. The numbers in the list are specified based on the argument passed. Since the range() function returns each number lazily, it is commonly used in ‘for’ loops.In case you have used Python 2, you might have come across the xrange() function. The range() function in Python 3 is a renamed version of the xrange().
The range() method also allows us to specify where the range should start and stop. Additionally, you can also pass an incrementer, the default is set to 1.
Syntax:
range(start, stop, increment)
Parameters:
- Start - Optional, used to specify where the range should start. The default start value is 0.
- Stop - Required, used to specify where the range should stop.
- Increment - Optional, used to specify the incrementation.
Code and Explanation:
#if only one argument is passed, Python assumes that it is a stop value.
for i in range(5):
print(i)
The output of the above code is:0
1
2
3
4
Example using the Start and Stop Arguments:
#Using a start and a stop value
for i in range(2,5):
print(i)
The output of the above code is:
2
3
4
Example using all three arguments:
for i in range(2,10,2):
print(i)
The output of the above code is:
2
4
6
8
Reversing a range:
It is common to reverse a list of values in the range. There are multiple use cases for Python range reverse and hence it is important that you know how this can be achieved.For this, we use the reversed() function in Python. This function reverses the arguments passed.
Code and Explanation:
for i in reversed(range(2,10,2)):
print(i)
The output of the above code is:8
6
4
2
This is how you can use Python range to reverse a list of numbers.
Points to remember - Python range reverse:
- Negative values can be passed as an increment in order to decrement the output.
- Passing the increment as 0 would return an error message
- The range method only works on integers.