Print a list in reverse order with range()?


How can you produce the following list with range() in Python?

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
7/28/2016 11:39:03 AM

Accepted Answer

use reversed() function:


It's much more meaningful.


If you want it to be a list (as btk pointed out):



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 [5,4,3,2,1,0], you can use the following:

range(5, -1, -1)

It may be less intuitive but as the comments mention, this is more efficient and the right usage of range for reversed list.

1/22/2017 9:42:56 PM

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)   
    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> range(-2, 6, 2)
    [-2, 0, 2, 4]

In Python 3, this produces a non-list range object, which functions effectively like a read-only list (but uses way less memory, particularly for large ranges).

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow