Use reversed() function (efficient since range implements __reversed__):
reversed(range(10))
It's much more meaningful.
Update: list cast
If you want it to be a list (as @btk pointed out):
list(reversed(range(10)))
Update: range-only solution
If you want to use only range to achieve the same result, you can use all its parameters. range(start, stop, step)
For example, to generate a list [3, 2, 1, 0], you can use the following:
range(3, -1, -1)
It may be less intuitive, but it works the same with less text. This answer by @Wolf indicates this approach is slightly faster than reversed.
Use reversed() function (efficient since range implements __reversed__):
reversed(range(10))
It's much more meaningful.
Update: list cast
If you want it to be a list (as @btk pointed out):
list(reversed(range(10)))
Update: range-only solution
If you want to use only range to achieve the same result, you can use all its parameters. range(start, stop, step)
For example, to generate a list [3, 2, 1, 0], you can use the following:
range(3, -1, -1)
It may be less intuitive, but it works the same with less text. This answer by @Wolf indicates this approach is slightly faster than reversed.
Use the 'range' built-in function. The signature is range(start, stop, step). This produces a sequence that yields numbers, starting with start, and ending if stop has been reached, excluding stop.
>>> range(9,-1,-1)
range(9, -1, -1)
>>> list(range(9,-1,-1))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> list(range(-2, 6, 2))
[-2, 0, 2, 4]
The list constructor converts range (which is a python generator), into a list.
Reversing a range using a FOR LOOP
iteration - How to loop backwards in python? - Stack Overflow
Why isn't my loop iterating backwards in python?
Is there a way to reverse a for loop
Can I combine reverse range with other Python functions or libraries?
Can I use reverse range with non-numeric values, such as strings or objects?
Are there any performance considerations when using reverse range?
Videos
I'm doing self-study program in Python and I'm being challenged to create a function that act exactly like the RANGE function, but it reverse the range. Let's call it reverserange().
reverserange(0,5) will return tuple (4, 3, 2, 1, 0)
I can't for the life of me figure it out. I've been trying for a couple hours. I know it requires a for loop...
Can anyone assist?
range() and xrange() take a third parameter that specifies a step. So you can do the following.
range(10, 0, -1)
Which gives
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
But for iteration, you should really be using xrange instead. So,
xrange(10, 0, -1)
Note for Python 3 users: There are no separate
rangeandxrangefunctions in Python 3, there is justrange, which follows the design of Python 2'sxrange.
for x in reversed(whatever):
do_something()
This works on basically everything that has a defined order, including xrange objects and lists.